getline не работает в switch, а cin не принимает данные соответствующим образом?Кто-нибудь может помочь? - PullRequest
3 голосов
/ 11 мая 2011

Привет, ребята, я работаю над проектом для моей работы, но, похоже, не могу понять это.

Мне нужно принять во внимание марку и год автомобиля, который подходит конкретному продукту. Программа напишет файл с текстом, который будет наброском HTML, который мне нужен, с важной информацией, вставленной в правильные места, чтобы быстро иметь возможность добавлять товары на нашу веб-страницу. Когда я использую операторы switch или if для разделения категорий продуктов, ввод вводится в заблуждение и не позволяет мне ответить на один из вопросов. Я не могу просто использовать cin, потому что мне нужно взять даты, которые выглядят как «2008 - 2009 - 2010 - 2011»

Вот что у меня так далеко! Это просто cin, я попробовал getline, вы могли бы быстро c я начал вчера, и я довольно новичок, так что простите, если это легко исправить, но я ничего не могу найти.

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

void proinfo();

int main()
{
    //Sytem Information
    system("TITLE This is a Beta of My Product Information Template Version 0.0.2");

    //I'm using this as a welcome screen to inform users of new improvements on patches and other pertinent information to the users
    cout << "Welcome To My Product Information Template Maker!!! \n It Is Still In Development" << endl;
    cout << "\n\nworking features are:" << endl << "\t-None\n" << endl;
    system("PAUSE");
    system("CLS");
    proinfo();
}

void proinfo()
{
    //Declare Variables here
    int loop(1), protype;
    char make[256], model[256], year[256];
    string getinput;

    while(loop==1)
    {
        //This is the first menu the user sees where they have to choose what type 
        //of products users will be adding
        system("CLS");
        cout << "Welcome to My Product Information Template Version 0.0.0" << endl;

        cout << "Please select the number of the product" << endl;
        cout << "type you will be ading!\n" << endl;

        cout << "1.Fe - Fe2 Moldings" << endl;
        cout << "2.CF - CF2 Moldings" << endl;

        cout << "What would you like to do? ";

        cin >> protype;

        if(protype==1)
        {
            //FE - FE2 Molding
            system("cls");

            cout << "You have selected" << endl;
            cout << "Fe - Fe2 Moldings\n" << endl;

            cout << "Please Enter the Make of the molding" << endl;
            cin >> make;

            cout << "Please Enter the Model of the molding" << endl;
            cin >> model;

            cout << "Please Enter the Years this molding fits" << endl;
            cin >> year;

            cout << "You have just created a template for a(n)" << year << " " << make << " " << model << endl;
            cout << "Check My Documents For a file called Fe-Fe2template.txt" << endl;

            //Asks to quit or restart
            cout << "Would you like to make another tempalte?" << endl;

            cin >> getinput;

            if(getinput=="yes")
            {
                cout << "Great, Lets keep working!" << endl;
                //End of If statement
            }

            system("PAUSE");
        }

        if(protype==2)  
        {
            //CF - CF2 Molding
            system("cls");

            //Asks to quit or restart
            cout << "Would you like to make another tempalte?" << endl;

            cin >> getinput;

            if(getinput=="yes")
            {
                cout << "Great, Lets keep working!" << endl;
                //End of If statement                   
            }

            system("PAUSE");

            //End of Protype Switch Statement               
        }

        //End of while loop              
    }
    //End of Proinfo()    
}

1 Ответ

5 голосов
/ 11 мая 2011

Изменить год [256] на год строки;

Изменить cin >> год;getline (cin, year);

Добавьте строку cin.ignore ();до getline.

Ваша основная проблема заключается в том, что оператор потока >> оставляет новую строку в потоке, поэтому при попытке использовать getline он читает пустую строку.ignore () сожжет новую строку и позволит вам прочитать ожидаемую строку.

Так что это должно помочь вам в этом.

cin.ignore();
cout << "Please Enter the Years this molding fits" << endl;
getline(cin, year);

У вас есть другие небольшие проблемы, но вы 'разберусь с нимиХуже всего забыть прекратить цикл.

if(getinput=="yes")
{
    cout << "Great, Lets keep working!" << endl;
   //End of If statement
}
else
{
    loop = 0;
    continue;
}
...