Switching from formatted to unformatted input in C++

可紊 提交于 2019-12-20 07:26:16

问题


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

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".

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.


回答1:


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.

You can use it like that:

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);


来源:https://stackoverflow.com/questions/39677197/switching-from-formatted-to-unformatted-input-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!