2017-03-01 52 views
0

我在读取文件输入行时遇到问题。这是一个非常简单的任务,我可以管理,但问题是输入文件行可以由单词和数字组成,然后我必须单独读取它们并将它们存储在不同的变量中。让我举个例子(斜体):尝试解析从输入文件读取的行

BOOK 100 
PENCIL  45 
LAPTOP 49 
SPOON    34 

无论Word和数字之间有多少空格,阅读操作都可以工作。

我写了这段代码直接读取行。但根据我放弃的信息,我不知道如何解析它们。

string fileName; 
     cout << "Enter the name of the file: "; 
     cin >> fileName; 

     ifstream file; 
     file.open(fileName); 

     while(file.fail()) 
     { 
      cout << "enter file name correctly:"; 
      cin >> fileName; 
      file.open(fileName); 
     } 

     string line; 
     int points; 


     while(!file.eof()) 
     { 
      getline(file, line); 
      stringstream ss(line); 

        *I do not know what to do here :)* 
        } 
+0

'eof()'是导致无尽的麻烦的原因。试试'while(std :: getline(file,line){... use line}' – BoBTFish

回答

3

但我不知道如何根据我放弃了信息解析。

那很简单,见下面的例子:

std::stringstream ss("SPOON    34"); 
std::string s; 
int n; 
if (ss >> s >> n) { 
    std::cout << s <<"\n"; 
    std::cout << n <<"\n"; 
} 

输出:

SPOON 
34 
0

您可以使用sscanf

char name[100]; 
int number; 
sscanf(line, "%s %d", name, &number); 
printf("%s, %d", name, number); 

现在我不确定这真的是C++ ish。像你已经开始使用stringstreams的替代方案。