无法多次输入值

时间:2014-06-30 14:08:23

标签: c++ variables input cin

我刚刚开始使用C ++,现在我在一个非常简单的程序中遇到了问题。我成功输入了part_num和part_des(两个类型字符串),但是程序跳过了part_price和part_quant(类型为int)。我无法输入这两个最后变量的值。如何解决这个问题?感谢

#include <iostream>
using namespace std;

int main()
{
string part_num;
string part_des;
int part_price;
int part_quant;

cout<<"Please enter the part number: ";
cin>>part_num;
cout<<"\n"<<endl;

cout<<"Please enter the part description: ";
cin>>part_des;
cout<<"\n"<<endl;

cout<<"Please enter the part price: ";
cin>>part_price;
cout<<"\n"<<endl;

cout<<"Please enter the part quantity: ";
cin>>part_quant;
cout<<"\n"<<endl;
}

3 个答案:

答案 0 :(得分:1)

发生了什么

请自己测试一下:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string my_string;
    cout << "enter a string: ";
    cin >> my_string;
    cout << "you have entered: " << my_string << endl;
    system("pause");
}

结果:

enter a string: one
you have entered: one
Press any key to continue . . .

enter a string: one two
you have entered: one
Press any key to continue . . .

“两个”在哪里?它仍然在流。当你在此之后尝试得到一个数字时,这段文字会自动作为你的输入,可能会出现异常并且程序突然结束。

如何修复

使用类似getline的内容。

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string my_string;
    cout << "enter a string: ";
    getline (cin, my_string);
    cout << "you have entered: " << my_string << endl;
    system("pause");
}

这将消除您遇到的问题。

enter a string: one two
you have entered: one two
Press any key to continue . . .

答案 1 :(得分:0)

代码工作正常。 (如果你没有空格)

#include <iostream>
using namespace std;

int main()
{
    string part_num;
    string part_des;
    int part_price;
    int part_quant;

    cout<<"Please enter the part number: ";
    cin>>part_num;
    cout<<"\n" << part_num <<endl;

    cout<<"Please enter the part description: ";
    cin>>part_des;
    cout<<"\n" << part_des <<endl;

    cout<<"Please enter the part price: ";
    cin>>part_price;
    cout<<"\n" << part_price <<endl;

    cout<<"Please enter the part quantity: ";
    cin>>part_quant;
    cout<<"\n" << part_quant <<endl;
}

http://ideone.com/U31pb9

立即给自己输出。看看你错过了什么。

修正了whitespaces的东西:

int main()
{
    string part_num;
    string part_des;
    int part_price;
    int part_quant;

    cout<<"Please enter the part number: ";
    getline( cin , part_num );
    cout << "\n" << part_num <<endl;

    cout<<"Please enter the part description: ";
    getline( cin , part_des );
    cout<< "\n" << part_des <<endl;

    cout<<"Please enter the part price: ";
    cin >> part_price;
    cout << "\n" << part_price <<endl;

    cout << "Please enter the part quantity: ";
    cin >> part_quant;
    cout << "\n" << part_quant <<endl;
}

另外考虑使用字符串作为价格和数量,然后如果你想继续使用getline,则将它们转换为整数。

答案 2 :(得分:-1)

试试这个,它应该有效:

#include <iostream>
using namespace std;

int main ()
{
  int i;
  cout << "Please enter an integer value: ";
  cin >> i;
  cout << "The value you entered is " << i;
  cout << " and its double is " << i*2 << ".\n";
  return 0;
}