将用户输入保存到文本文件c ++

时间:2016-03-11 02:27:02

标签: c++ c++11 file-io user-input

我一直在编写一个模拟计算机终端的程序。其中一个选项是编写一些文本并将其保存到现有的文本文件中,但是我一直无法将整个输入保存到文件中。

这是触发写入文件的原因:

else if(command == "write"){
   ofstream myfile (arg.c_str());
   string writeToFile;
   std::cout << "Opening file '"<< arg.c_str() << "'...\n" << std::endl;
   std::cout << "Plese enter what you want to write into the file:\n" << std::end;

   std::getline(std::cin, writeToFile);

   if (myfile.is_open()){
     myfile << writeToFile << "\n";
     myfile.close();
   }

   std::cout << "You wrote: " << writeToFile << std::endl;
   std::cout << "File succesfully updated. \n" << std::endl;
   commandStart();
 }

然而,当我使用std::getline(std::cin, writeToFile);时,这就是结果: Using std::getline(std::cin, writeToFile);

它不允许我输入任何内容保存到文件中然后自动关闭,但是,当我使用它时:

else if(command == "write"){
   ofstream myfile (arg.c_str());
   string writeToFile;
   std::cout << "Opening file '"<< arg.c_str() << "'...\n" << std::endl;
   std::cout << "Plese enter what you want to write into the file:\n" << std::end;

   std::cin >> writeToFile;

   if (myfile.is_open()){
     myfile << writeToFile << "\n";
     myfile.close();
   }

   std::cout << "You wrote: " << writeToFile << std::endl;
   std::cout << "File succesfully updated. \n" << std::endl;
   commandStart();
 }

使用std::cin >> writeToFile;我允许输入内容并将其保存到文件中,但它只保存第一个单词:

Using std::cin >> writeToFile;

有关为何发生这种情况的任何想法? 我已经检查了其他问题和网站,但我还没有能够解决这个问题。

1 个答案:

答案 0 :(得分:0)

基本上cout'\ n'由你的getline函数读取。 cout()之后的std :: cin.ignore()将解决您的问题。

正如MikeCAT Why does std::getline() skip input after a formatted extraction?所述,答案深入解释原因,绝对值得一读。

相关问题