我正在尝试制作一个程序,它将获取用户输入的新文件名,创建文件并写入文件。它可以工作,但它只会将字符串的第一个单词写入文件。如何让它写出完整的字符串?感谢。
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
for (;;)
{
char *myFile = " ";
string f = " ";
string w = " ";
cout <<"What is the name of the file you would like to write to? " <<endl;
cin >>f;
ofstream myStream(f,ios_base::ate|ios_base::out);
cout <<"What would you like to write to " <<f <<" ? ";
cin >>w;
myStream <<w;
if (myStream.bad())
{
myStream <<"A serious error has occured.";
myStream.close();
break;
}
}
}
答案 0 :(得分:1)
根据this post,您应该咨询this reference以使用getline()等方法。
另外,当你写出来时,我建议你在结束程序之前刷新输出(cout.flush()),特别是在这种情况下,因为我认为你是以ctrl-C中断结束程序。 / p>
在制定建议时,我会将数据读入char *,并将它们转换为“string”,以防您在程序的其他地方使用它们。
我在MS Visual C ++ Express中测试了这段代码。
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
for (;;)
{
char *myFile = new char[200]; // modified this line
//added this line
char *myInput = new char[200];
string f = " ";
string w = " ";
cout << "What is the name of the file you would like to write to? " << endl;
cin.getline(myFile, 200);//modified this line
f = (myFile);//added this line
cin.clear(); //added this line
ofstream myStream(f, ios_base::ate | ios_base::out);
cout << "What would you like to write to " << f << " ? ";
cin.getline(myInput, 200);//edited this line
w = string(myInput);//added this line
myStream << w;
myStream.flush();//added this line
if (myStream.bad())
{
myStream << "A serious error has occured.";
myStream.close();
break;
}
delete myFile;
delete myInput;
}
}
答案 1 :(得分:0)
您必须使用std::getline()
来阅读整行:
std::getline(std::cin >> std::ws, w);
>> std::ws
部分摆脱了所需的前导空格,因为前一次提取的流中留下的换行符会阻止std::getline()
完全消耗输入。
将数据插入流时,您需要确保它被刷新(因为,正如另一个答案所说,您可能正在使用 Ctrl + C 来终止程序而您可能看不到程序运行期间的输出)。您可以使用std::flush
操纵器来刷新输出:
myStream << w << std::flush;
答案 2 :(得分:0)
cin<<w;
cin在遇到空格标签和其他不可见字符时会停止使用输入字符。
您应该使用std::getline()
代替。
看看这个页面的参考。
http://en.cppreference.com/w/cpp/string/basic_string/getline
或者你可以使用操纵器来跳过空格。