[问题] 文件写入问题

楼主: akka5678   2015-12-21 19:56:04
我要写入一个文件档,键盘输入 姓名 电话 Email
如下:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
ofstream myFile;
int n = 0;
char str1[50];
char str2[50];
myFile.open("Ex15_1.dat",ios::out)
cout << "请输入姓名、电话、Email地址" << endl;
while(1)
{
cin >> str1 >> n >> str2;
if (!strlen(str1) ==0) //若字串长度不等于0
{
myFile << str1 << '\t' << n << '\t' << str2 << endl;
}
else
break;
}
myFile.close();
return 0;
}
结果按Enter不会中断这个循环而且会一直复制
例如 我输入 police 110 gmail
hospital 119 hotmail
文件档会是最后一行输入的一直复制
police 110 gmail
hospital 119 hotmail
hospital 119 hotmail
hospital 119 hotmail
hospital 119 hotmail
hospital 119 hotmail
hospital 119 hotmail
hospital 119 hotmail
hospital 119 hotmail
.....
想了很久,不知道要怎么修正,求解
作者: flydragon198 (Richard)   2015-12-21 20:11:00
(!strlen(str1) ==0) 这里有问题
楼主: akka5678   2015-12-21 20:18:00
因为我想用Enter结束,不就是str1字串长度==0时break吗?
作者: flydragon198 (Richard)   2015-12-21 20:22:00
在cin后,会一直重复循环,没有输入就会一直重复
楼主: akka5678   2015-12-21 20:28:00
对,但没有输入就按Enter不就是字串长度=0?怎么没中断QQ例如我输入了两行资料第三行不输入了,直接按Enter想离开
作者: stupid0319 (征女友)   2015-12-21 20:31:00
if中再加一行ZeroMemory(str1,50);
作者: flydragon198 (Richard)   2015-12-21 20:32:00
cin如果直接按enter,不会把字串变成空的样子你可以在while内第一行加上cout << "test";然后开启程式直接按enter,会发现进不去while因为一直停留在前一行的cin另外你的if内也没有改变str1的值,他就会变成在while内无穷循环,不会跳出
作者: LPH66 (-6.2598534e+18f)   2015-12-21 21:47:00
stringstream 可以解决你的问题

Links booklink

Contact Us: admin [ a t ] ucptt.com