C++中字符串读取getlien函数问题求教!

shtianhai 2008-05-01 08:34:01
问题:如何从控制台读取一行到一个字符串(一行中可以有空格)
我试了用getline(),但是要按两次回车,才可以执行下一行,即下面的“ cout << "ok" << endl;”,这是为何?
#include <iostream>
#include <string>

using namespace std;

int main()
{
string s;
string str = "l love ";

getline(cin,s);

cout << "ok" << endl;
str += s;

cout << str << endl;

cout << s << endl;
return 0;

}

如何才可以解决从控制台读取一行到一个字符串(一行中可以有空格)?
请大虾们指教指教!
...全文
246 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
meiZiNick 2008-05-02
  • 打赏
  • 举报
回复
有点难度哦
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 Jncryang 的回复:]
是微软的STL的一个bug, 它在读stream 的时候,总要试图预读一个char 来判断是否eof。
对文件操作没问题,对键盘输入,就会出现打两次回车的问题。
在Unix/Linux 就没这样的问题。
[/Quote]
shtianhai 2008-05-02
  • 打赏
  • 举报
回复
六楼和四楼差不多,5和7楼的也要两遍回车,看来这个BUG是解决不了了!
shtianhai 2008-05-02
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 bitxinhai 的回复:]
#include   <iostream>
#include   <string>

using namespace std;

int main()
{
string s;
string str = "l love ";

cin。ignore(256,‘/n’);


getline(cin,s);

cout   <  < "ok"   <  < endl;
str += s;

cout   <  < str   <  < endl;

cout   <  < s   <  < endl;
return 0;

}
[/Quote]

和我在四楼说的差不多,不是根本问题,仍然不可以解决大小的限制,
5楼和7楼的也是要敲两遍回车才行!
我想的只是输入一行(可以有空格) 然后回车,就可以了!
flysnowboy 2008-05-02
  • 打赏
  • 举报
回复
#include   <iostream>   
#include <string>

using namespace std;

int main()
{
string s;
string str = "l love ";

cin.ignore(256,‘/n’);


getline(cin,s);

cout < < "ok" < < endl;
str += s;

cout < < str < < endl;

cout < < s < < endl;
return 0;

}
hujinyong199 2008-05-01
  • 打赏
  • 举报
回复
void _GetLine(string &str, char delim='\n')
{
char Text[128];
Text[0]='\0';

cin.getline(Text,127,delim);
str=Text;
}
bitxinhai 2008-05-01
  • 打赏
  • 举报
回复
#include <iostream>
#include <string>

using namespace std;

int main()
{
string s;
string str = "l love ";

cin。ignore(256,‘/n’);


getline(cin,s);

cout < < "ok" < < endl;
str += s;

cout < < str < < endl;

cout < < s < < endl;
return 0;

}
shtianhai 2008-05-01
  • 打赏
  • 举报
回复
除了这个解决办法就没有办法读到字符串里了吗?
毕竟char不是string,有数组大小限制。
#include<iostream.h>
void main()
{
char str[80];
cin.getline(str,80);
cout<<str<<endl;
}
iu_81 2008-05-01
  • 打赏
  • 举报
回复
getline以回车('\n')作为结束符,第一次按回车表示字符串结束,第二次按回车才开始输出。
Jncryang 2008-05-01
  • 打赏
  • 举报
回复
是微软的STL的一个bug, 它在读stream 的时候,总要试图预读一个char 来判断是否eof。
对文件操作没问题,对键盘输入,就会出现打两次回车的问题。
在Unix/Linux 就没这样的问题。

70,037

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧