注册 登录
编程论坛 C++教室

文件读取姓名操作出现问题

最近不在 发布于 2010-07-13 08:58, 333 次点击
程序代码:
string a;
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;
}



[ 本帖最后由 最近不在 于 2010-7-13 09:05 编辑 ]
2 回复
#2
东海一鱼2010-07-13 11:45
这个跟具体的库实现有关。
vc6下,getline在读取一行输入时,如果没遇到文件结尾标志,或已经到最大行字符数,仅输入'\n'它并不立即返回.它需要遇到指定的'定界符'才返回.

如:
string strName
getline(cin,strName,'\\ ').
遇到'\\'才返回。

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;
}


[ 本帖最后由 东海一鱼 于 2010-7-13 11:47 编辑 ]
#3
最近不在2010-07-13 13:27
回复 2楼 东海一鱼
太感谢你了,书上都没写getline这种用法。原来是第一个小问题,造成了第二个大问题,一语道破。
1