c++ - 文件输入和处理数据

标签 c++ ifstream

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

方法一
方法二
插入3个“James Tan”

我目前正在使用 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 不快,我还有什么其他选择。

请指教。

最佳答案

Method 1
Method 2
Insert 3 "James Tan"

我认为你的意思是文件由几行组成。每行以“方法”一词或“插入”一词开头,在每种情况下都后跟一个数字。此外,以“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
}

关于c++ - 文件输入和处理数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14859194/

相关文章:

c++ - 使用 DrawingSurfaceBackgroundGrid 重新绘制框架的正确技术是什么? (DirectX + xaml 应用程序)

c++ - 将 2 个结构数组的信息输出到一个文件中

c++ - 处理错误的 ifstream

C++:使用ifstream读取大型pgm文件

c++ - 无法解析 cc1plus : error: unrecognized command line option "-std=c++11"

c++ - 如果不是第一响应者,为什么我可以单击 NSButton?

c++ - 如何在 C++Builder 中运行两个窗体

c++ - 有 C++ 惰性指针吗?

c++ - 使用 C++ 读取一行数字

c++ - 使用 C++ ifstream 提取运算符>> 从文件中读取格式化数据