c++ - 在 C++ 中逐行读取并从行中获取单词

标签 c++ getline

string line;
string filename;
cout << "Please enter filename :" << endl;
cin >> filename;
ifstream myfile(filename);
/*cout << "Please enter the name of file that you write results : "<< endl;
cin >> wfile; */
if(myfile.is_open())
{

    while(getline(myfile,line))
    {
        convert(line);

    }

    //getline(myfile,line);
    //pushintoVector(line,buffer);
}
else
{
    cout << "Error : File could not be opened" << endl;

}

try{
myfile.close();
myFile.close();
}catch(exception &e1)
{
    cout << endl;
}
//system("PAUSE");
return 0;

之后我想将当前行发送到另一个函数,例如:

void convert(string lines)
{
    myFile.open("yazici.txt");

    string buf;
     string convertingnum;
    istringstream ss(lines);

    while(ss >> buf)
    {                

那么我如何从一行中读取单词并根据 if-else 结构更改它并将其写入另一个文件。编辑:还有确定行长度的函数或方法吗?

最佳答案

  1. 在打开输入文件的同时打开输出文件。
  2. 将输出流作为参数传递给 convert,而不是每次都在函数中打开文件。
  3. 使用比 myfilemyFile 更好的名称。
ifstream inputFile(filename);
ofstream outputFile("yazici.txt");

if(inputFile.is_open())
{
   while(getline(inputFile,line))
   {
      convert(outputFile, line);
   }
}

和...

void convert(std::ostream& outputFile,
             string lines)
{
   string buf;
   string convertingnum;
   istringstream ss(lines);

   while(ss >> buf)
   {
       outputFile << buf << std::endl; //???
   }
}

关于c++ - 在 C++ 中逐行读取并从行中获取单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33600771/

相关文章:

c++ - 移动设备上的 SDL2 事件

c++ - 是否有任何规则禁止在更改器(mutator)中放置多个参数?

c++ - 设置一个等于自身的变量实际上在 C++ 中执行吗?

c++ - 当从文件中使用 getline 时,While Loop 只循环一次

c++ - 有没有一种方法可以使用 cin.getline() 而不必事先定义 char 数组大小?

c++ - 检测类中使用 CRTP 的成员函数

c++ - 用perf和papi测量L1数据缓存未命中

c++ - 从 'int' 到 'char *' 的无效转换

c++ - 如何分隔字符串并将每个部分存储在不同的 vector 中

C++ - 将 .csv 文件读入 vector ,同时跳过第一行和特定列