在C ++中从格式化输入切换为未格式化输入 [英] Switching from formatted to unformatted input in C++

查看:80
本文介绍了在C ++中从格式化输入切换为未格式化输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入文本文件.第一行有两个 int 数字 a b ,第二行是字符串.我想使用格式化的输入来执行 file>>一个>>b ,然后进行未格式化的输入以一一获取字符串的字符.在两个步骤之间,我需要跳过第一行末尾的'\ n'字符.我用过

I have an input text file. The first line has two int numbers a and b, and the second line is a string. I want to use formatted input to do file >> a >> b, and then unformatted input to get the characters of the string one by one. In between the two steps, I need to skip over the '\n' character at the end of the first line. I used

  while(file.get()<=' ' && !file.eof());  // skip all unprintable chars
  if(!file.eof()) file.unget();           // keep the eof sign once triggered

使输入格式更灵活.用户现在可以使用任意数量的空行'\ n'和制表键'\ t'和/或空格键''-他必须自由地分隔数字 a b .现在,在Linux上读取从Windows复制的文本文件时甚至没有问题,此时每行的结尾都变为"\ r \ n" .

to make the input format more flexible. The user can now separate the numbers a and b from the string using an arbitrary number of empty lines '\n', tab keys '\t', and/or space keys ' ' -- the same freedom he has to separate the numbers a and b. There's even no problem reading in Linux a text file copied from Windows when every end of line now becomes "\r\n".

是否有一个执行相同功能的 ifstream 函数(跳过所有字符< ='',直到下一个可打印的字符或 EOF 到达了)? ignore 函数似乎没有做到这一点.

Is there an ifstream function that does the same thing (skip all chars <=' ' until the next printable char or EOF is reached)? The ignore function does not seem to do that.

推荐答案

是的,有:

Yes, there is: std::ws manipulator. It skips whitespace characters until a non-whitespace is found or end of stream is reached.. It is similar to use of whitespace character in scanf format string.

实际上,格式化输入会在实际开始解析字符之前使用它.

In fact, it is used by formatted input before actually starting to parse characters.

您可以这样使用它:

int x;
std::string str;
std::cin >> x >> std::ws;
std::getline(std::cin, str);
//...
//std::vector<int> vec;
for(auto& e: vec) {
    std::cin >> e;
}
std::getline(std::cin >> std::ws, str);

这篇关于在C ++中从格式化输入切换为未格式化输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆