![]() |
#2
东海一鱼2010-07-13 11:45
|

string a;
getline(cin, a);
为什么要输入2次回车,才结束。怎样才能输入一次回车结束,避免用户不知道这情况!
getline(cin, a);
为什么要输入2次回车,才结束。怎样才能输入一次回车结束,避免用户不知道这情况!
大问题。我结构体里2个string成员, 用getline读取姓名这种有空格的字符串,文件流出现问题。普通无空格用cin的没问题,希望大家能帮帮我,我弄了很久无法解决。顺带问下,从文件中读取数字,是如何实现的。是想用字符串读取内容,再转换为数值?

// Note:Your choice is C++ IDE
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
using namespace std;
struct cmd
{
string a;
string b;
friend ostream& operator << (ostream &os, const cmd& t);
friend istream& operator >> (istream &is, cmd& t);
};
ostream& operator << (ostream &os, const cmd& t)
{
//cin.sync();
os<<t.a<<'\t'<<t.b;
return os;
}
istream& operator >> (istream &is, cmd& t)
{
//is>>t.a>>t.b>>t.c;
//cin.sync();
getline(is, t.a);
getchar();
getline(is, t.b);
return is;
}
int main()
{
cmd a[2];
cmd b;
vector<cmd> obj;
ofstream outfile("g:\\ct.txt", ios_base::app | ios_base::out);
for(int i = 0 ; i != 2; ++i)
{
cin>>a[i];
outfile<<a[i]<<endl;
}
outfile.close();
outfile.clear();
ifstream infile("g:\\ct.txt");
while(!infile.eof())
{
infile>>b;
obj.push_back(b);
cout<<b<<endl;
}
for(vector<cmd>::iterator iter = obj.begin(); iter != obj.end(); ++iter)
{
cout<<*iter<<endl;
}
infile.close();
return 0;
}
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
using namespace std;
struct cmd
{
string a;
string b;
friend ostream& operator << (ostream &os, const cmd& t);
friend istream& operator >> (istream &is, cmd& t);
};
ostream& operator << (ostream &os, const cmd& t)
{
//cin.sync();
os<<t.a<<'\t'<<t.b;
return os;
}
istream& operator >> (istream &is, cmd& t)
{
//is>>t.a>>t.b>>t.c;
//cin.sync();
getline(is, t.a);
getchar();
getline(is, t.b);
return is;
}
int main()
{
cmd a[2];
cmd b;
vector<cmd> obj;
ofstream outfile("g:\\ct.txt", ios_base::app | ios_base::out);
for(int i = 0 ; i != 2; ++i)
{
cin>>a[i];
outfile<<a[i]<<endl;
}
outfile.close();
outfile.clear();
ifstream infile("g:\\ct.txt");
while(!infile.eof())
{
infile>>b;
obj.push_back(b);
cout<<b<<endl;
}
for(vector<cmd>::iterator iter = obj.begin(); iter != obj.end(); ++iter)
{
cout<<*iter<<endl;
}
infile.close();
return 0;
}
[ 本帖最后由 最近不在 于 2010-7-13 09:05 编辑 ]