如何在 C++ 中读取格式化数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3555715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 13:06:47  来源:igfitidea点击:

How to read formatted data in C++?

c++stringiostreamifstreamstring-parsing

提问by TheOnly92

I have formatted data like the following:

我已经格式化了如下数据:

Words          5
AnotherWord    4
SomeWord       6

It's in a text file and I'm using ifstream to read it, but how do I separate the number and the word? The word will only consist of alphabets and there will be certain spaces or tabs between the word and the number, not sure of how many.

它在一个文本文件中,我正在使用 ifstream 来读取它,但是如何将数字和单词分开?单词将仅由字母组成,单词和数字之间会有某些空格或制表符,不确定有多少。

回答by Donotalo

Assuming there will not be any whitespace within the "word" (then it will not be actually 1 word), here is a sample of how to read upto end of the file:

假设“单词”中没有任何空格(那么它实际上不会是 1 个单词),这里是如何读取文件末尾的示例:

std::ifstream file("file.txt");
std::string str;
int i;

while(file >> str >> i)
    std::cout << str << ' ' << i << std::endl;

回答by user151019

The >> operator is overridden for std::stringand uses whitespace as a separator

>> 运算符被std::string覆盖,并使用空格作为分隔符

so

所以

ifstream f("file.txt");

string str;
int i;
while ( !f.eof() )
{
  f >> str;
  f >> i;
  // do work
}

回答by Stefan Steiger

sscanf is good for that:

sscanf 对此有好处:

#include <cstdio>
#include <cstdlib>

int main ()
{
  char sentence []="Words          5";
  char str [100];
  int i;

  sscanf (sentence,"%s %*s %d",str,&i);
  printf ("%s -> %d\n",str,i);

  return EXIT_SUCCESS;
}

回答by Default

It's actually very easy, you can find the reference here
If you are using tabs as delimiters, you can use getlineinstead and set the delim argument to '\t'. A longer example would be:

这实际上非常简单,您可以在此处找到参考
如果您使用制表符作为分隔符,则可以使用getline并将 delim 参数设置为 '\t'。一个更长的例子是:

#include <vector>
#include <fstream>
#include <string>

struct Line {
    string text;
    int number;
};

int main(){
    std::ifstream is("myfile.txt");
    std::vector<Line> lines;
    while (is){
        Line line;
        std::getline(is, line.text, '\t');
        is >> line.number;
        if (is){
            lines.push_back(line);
        }
    }
    for (std::size_type i = 0 ; i < lines.size() ; ++i){
        std::cout << "Line " << i << " text:  \"" << lines[i].text 
                  << "\", number: " << lines[i].number << std::endl;
    }
}