我有一個很大的問題... 只需運行該程序,然後轉到「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;
}
因爲'CIN >> gunModel;'獲取 「沙漠」,然後'函數getline(CIN,gunModel);'獲取「鷹」。嘗試刪除'cin >> gunModel;'。 – DimChtz
刪除cin,並添加getline? 是的,我試過但看看會發生什麼... 當我去添加一把槍它錯過了「型號:」,並剛剛開始在製造年...... –
編輯您的問題,並實施DimChtz的建議。你只需要刪除一行。 –