15

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.

4

4 回答 4

22

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

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

while(file >> str >> i)
    std::cout << str << ' ' << i << std::endl;
于 2010-08-24T11:31:45.013 回答
3

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

所以

ifstream f("file.txt");

string str;
int i;
while ( !f.eof() )
{
  f >> str;
  f >> i;
  // do work
}
于 2010-08-24T11:35:18.363 回答
3

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;
}
于 2010-10-19T10:37:41.517 回答
2

这实际上非常简单,您可以在此处
找到参考 如果您使用制表符作为分隔符,您可以使用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;
    }
}
于 2010-08-24T11:18:24.743 回答