【问题标题】:File input and process data文件输入和处理数据
【发布时间】:2013-02-13 17:19:35
【问题描述】:

我想从一个文本文件中读取,文件的格式是

方法一
方法二
插入 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 不快,我还有什么其他选择。

请对此提出建议。

【问题讨论】:

  • 你真的不应该做while (stream.good()) ...,你甚至不需要检查文件是否打开。只需打开文件,然后执行while (stream >> input >> input2) ...。

标签: c++ ifstream


【解决方案1】:

方法一
方法二
插入 3“詹姆斯·谭”

我认为您的意思是该文件由几行组成。每行要么以单词“Method”或单词“Insert”开头,在每种情况下都后跟一个数字。此外,以“插入”开头的行末尾有一个多词名称。

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

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-27
    • 1970-01-01
    • 1970-01-01
    • 2015-12-14
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多