2017-09-13 21 views
0

C++を使用する14。私はこの問題に関する多くの記事を読んだ。getline(cin、string)の出力が期待されない

このコードを実行すると、getline行にジャンプします。

#include <iostream> 
#include "main_menu.h" 

void MainMenu::AddTest() 
{ 
    std::string courseName = ""; 
    std::string testName = ""; 
    std::string date = ""; 

    std::cout << "Enter course name: " << std::endl; 
    std::getline(std::cin, courseName); 

    std::cout << "Enter test name: " << std::endl; 
    std::getline(std::cin, testName); 

    std::cout << "Enter test date: " << std::endl; 
    std::getline(std::cin, date); 

    Test test(courseName, testName, date); 
    tests.Add(test); 

    std::cout << "Test registered : " << std::endl; 
    tests.Print(test.id); 
} 

私はCIN各getlineのライン(私はそれを実装する方法以下の例)の後に無視を追加する場合は、入力文字列からいくつかの文字を削除し、それらを格納するために間違った変数を使用しています。私は空白文字列を持っていることに注意してください。

std::getline(std::cin, courseName); 
std::cin.ignore(); 

これは私が得るものです:

Enter course name: 
History 2 
Enter test name:  
History 2 exam 
Enter test date: 
2017.01.02 
Test registered : 
test id = 2, course name = , test name = istory 2, date = istory 2 exam 

私はまた、COUTをフラッシュしようとした助けにはなりませんでした。

私の印刷機能は魅力的に機能します。メインから手動でメインを追加すると、予想される出力が得られます。問題は間違いなくcin/getlineです。ここで説明したように

Test registered : 
test id = 1, course name = History 2, test name = History 2 exam , date = 01.02.2017 

私はgetl​​ineのを使用します。http://www.cplusplus.com/reference/string/string/getline/?kw=getline

すべてのヘルプははるかに高く評価されるだろう、ありがとうございました。

答えて

0

cin.ignoreを使用すると、入力自体が面倒になります。あなたは\n文字を取り除きたい場合は、あなたはする必要はありません! getlineは自動的にそれを行います。だからちょうどignore関数を使用しないとコードは正常になります。 これは動作します:

#include<iostream> 

using namespace std; 

int main() 
{ 
    string courseName = ""; 
    string testName = ""; 
    string date = ""; 

    cout << "Enter course name: " << std::endl; 
    getline(std::cin, courseName); 

    cout << "Enter test name: " << std::endl; 
    getline(std::cin, testName); 

    cout << "Enter test date: " << std::endl; 
    getline(std::cin, date); 

    cout << courseName << endl; 
    cout << testName << endl; 
    cout << date << endl; 
    return 0; 
} 
+0

私はcin.ignoreを使用しない場合、私はCIN自体を入力するように取得することはありません。プログラムは、入力を待つことなく、次のcoutに進みます。それは基本的に私の頭痛のリストです、それは私の最初の問題です。 @Sinapse –

+0

'cin.ignore'はあなたの入力した文字のうちの1つだけを渡します!上のコードをテストできますか?あなたのコンパイラは何ですか? – Sinapse

+0

あなたのコードは動作しますが、私はしません。プログラムは入力を待つことはありません。一番上のもの(cin.ignoreのないもの)の元のコードを見てください。違いはあまりありません。私はGDB clion btwを使用します。 –

関連する問題