c++从string中读取整行

C++ reading a whole line from string

本文关键字:读取 string c++      更新时间:2023-10-16

我有一个大问题…只要运行程序,点击"新枪",然后点击"手枪"。当您必须进入模型时,问题就出现了。例如,如果我输入"Desert Eagle",在文本文件中它只输出"Eagle"。真奇怪,我解不出来。

代码:

#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 << "nn";
        myfileHandguns << "Year of Manufacture: " << gunManufactureYear << "nn";
        myfileHandguns << "Weight: " << gunWeight << " g" << "nn";
        myfileHandguns << "Item Number: " << itemNumber << "nn";
        myfileHandguns << "Price: " << price << "$" << "nn";
        myfileHandguns.close();
    }
}
system("pause > nul");
return 0;

}

按建议删除>>操作符。使用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;

参见为什么我们要在读取输入后调用cin.clear()和cin.ignore() ?