2016-08-15 47 views
0

我有一个很大的问题... 只需运行该程序,然后转到“New Gun”,然后选择“Handgun”。 当您必须输入模型时,就会出现问题。 例如,如果我输入“沙漠之鹰”,在文本文件中它只输出“鹰”。它很奇怪,我无法解决它。从字符串中读取整行的C++

代码:

#include <fstream> 
#include <iostream> 
#include <windows.h> 
#include <string> 
#include <algorithm> 
#include <sstream> 
using namespace std; 

void setcolor(unsigned short color) 
{ 
HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE); 
SetConsoleTextAttribute(hcon,color); 
} 

int main(){ 

system("chcp 1251 > nul"); 
system("title GunnZone"); 


string gunModel; 
int gunManufactureYear; 
int itemNumber; 
double gunWeight; 
double price; 

ofstream myfileHandguns("Handguns.txt", ios::app); 
ofstream myfileRifles("Rifles.txt", ios::app); 
ofstream myfileShotguns("Shotguns.txt", ios::app); 
ofstream myfileSnipers("Snipers.txt", ios::app); 
ofstream myfileGranades("Granades.txt", ios::app); 
ofstream myfileExplosives("Explosives.txt", ios::app); 


int choice; 
cout << "1.New Gun" << endl; 
cout << "2.List Guns" << endl; 
cout << "3.Exit" << endl << endl; 
cout << "Enter your choice: "; 
cin >> choice; 

if(choice == 1){ 

    system("cls"); 

    int gunTypeChoice; 
    cout << "1.Handgun" << endl; 
    cout << "2.Rifle" << endl; 
    cout << "3.Shotgun" << endl; 
    cout << "4.Sniper" << endl; 
    cout << "5.Granade" << endl; 
    cout << "6.Explosives" << endl << endl; 
    cout << "Enter your choice: "; 
    cin >> gunTypeChoice; 

    if(gunTypeChoice == 1){ 

     system("cls"); 

     cout << "Model: "; 
     cin >> gunModel; 
     getline(cin, gunModel); 
     cout << endl << endl; 

     cout << "Year of Manufacture: "; 
     cin >> gunManufactureYear; 
     cout << endl << endl; 

     cout << "Weight: "; 
     cin >> gunWeight; 
     cout << endl << endl; 

     cout << "Item Number: "; 
     cin >> itemNumber; 
     cout << endl << endl; 

     cout << "Price: "; 
     cin >> price; 


     myfileHandguns << "Model: " << gunModel << "\n\n"; 
     myfileHandguns << "Year of Manufacture: " << gunManufactureYear << "\n\n"; 
     myfileHandguns << "Weight: " << gunWeight << " g" << "\n\n"; 
     myfileHandguns << "Item Number: " << itemNumber << "\n\n"; 
     myfileHandguns << "Price: " << price << "$" << "\n\n"; 
     myfileHandguns.close(); 
    } 

} 

system("pause > nul"); 
return 0; 

}

+3

因为'CIN >> gunModel;'获取 “沙漠”,然后'函数getline(CIN,gunModel);'获取“鹰”。尝试删除'cin >> gunModel;'。 – DimChtz

+0

删除cin,并添加getline? 是的,我试过但看看会发生什么... 当我去添加一把枪它错过了“型号:”,并刚刚开始在制造年...... –

+0

编辑您的问题,并实施DimChtz的建议。你只需要删除一行。 –

回答

2

删除>>操作者的建议。使用clearignore来清除错误跳过换行符\n

cout << "Model: "; 
//cin >> gunModel; 
std::cin.clear(); 
std::cin.ignore(0xffff, '\n'); 
std::getline(cin, gunModel); 
cout << "Testing... you entered " << gunModel << endl; 
cout << endl << endl; 

参见Why would we call cin.clear() and cin.ignore() after reading input?

+0

非常感谢你! 现在我明白了。 –

+0

您可以单击复选标记接受答案 –