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

Save user input to a text file c++

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

触发写入文件的原因如下:

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); 时,结果是这样的:

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

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; 我可以输入一些内容并将其保存到文件中,但它只保存第一个单词:

知道为什么会这样吗? 我已经检查了其他问题和网站,但我无法解决这个问题。

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

MikeCAT 提到的 Why does std::getline() skip input after a formatted extraction? 答案深入解释了原因,绝对值得一读。