2013-02-13 115 views
0

我想从一个文本文件中读取和文件的格式是文件输入和处理数据

方法1
方法2
插入3“詹姆斯谭”

我目前使用ifstream打开文本文件并读取项目,但是当我使用>>读取行时,导致名称不能完全读为“James Tan”。 下面附上的是代码和输出。

ifstream fileInput; 

    if(fileInput.is_open()){ 
     while(fileInput.good()){ 
    fileInput >>methondName>>value>>Name; 
    ...... 

输出

methodName = Method, Method, Insert 
value = 1, 2, 3 (must be a usigned integer) 
Name = James 

有什么更好的方式来处理线条和内容的阅读。 我被告知getline。但我明白,getline完全是作为一行而不是单个单词的单词。

接下来是fstream真的很快吗?原因,我想处理500000行数据,如果ifstream速度不快,我还有什么其他选项。

请对此提出建议。

+1

您不应该真正执行'while(stream.good())...',而且您甚至不需要检查文件是否打开。只要打开文件,并执行'while(stream >> input >> input2)...'。 – 2013-02-13 17:23:01

回答

3

方法1种
方法2
插入3 “詹姆斯谭”

我想你的意思是,该文件由几行组成。每一行都以单词“方法”或单词“插入”开头,每一行后面跟一个数字。此外,开始“插入”的行在结尾处具有多字词名称。

是吗?如果是这样,请尝试:

ifstream fileInput("input.txt"); 
std::string methodName; 
int value; 
while (fileInput >> methodName >> value) { 
    std::string name; 
    if(methodName == "Insert") 
    std::getline(fileInput, name); 

    // Now do whatever you meant to do with the record. 
    records.push_back(RecordType(methodName, value, name); // for example 
}