【发布时间】:2012-10-05 04:33:03
【问题描述】:
我已经编写了一个代码,用于在 C++ 中从用户那里获取字符串。这是代码
#include<iostream>
#include<string>
using namespace std;
string input;
void enterstring()
{
cout<<"\nEnter input: ";
getline(cin,input);
}
void displaystring()
{
cout<<"\nyour string is "<<input<<endl;
}
{
int main()
{
int choice=0;
while(choice!=3)
{
cout<<"Enter choice: "<<;
cin>>choice;
switch(choice)
{
case 1: enterstring();
break;
case 2: displaystring();
break;
case 3: cout<<"\nQuit";
break;
default: cout<<"\ninvalid choice try again";
break;
}
return 0;
}
以上代码的输出:
Enter choice: 1
Enter input:
Enter choice:
输入部分被跳过我不知道为什么问题出在哪里。逻辑错了,语法有什么问题。当我在不使用 while 循环等的情况下调用函数时,它工作正常,但在这种情况下它不起作用。帮帮我。
【问题讨论】:
-
尝试在 enterString() 函数中使用
cin>>input; -
A program shall contain a global function called main , which is the designated start of the program.--ISO/IEC 14882-2011 3.6.1 p1 -
@Shashwat 在我写一个字符串时使用了 cin>>输入假设“世界上到处都是自私的人”进入空格会产生无限循环。为了避免这种情况,我使用了 getline。
-
但我的程序包含主要功能。 @pwned。
-
我很惊讶为什么它跳过了主要功能..很奇怪。我编辑了很抱歉@Shashwat