2016-04-04 6 views
0

これは基本的な質問ですが、私は事前に謝罪してC++に新たなんだ:)ベクトルに保存されている文字列をプリントアウト

私はベクトルに保存されている文字列をプリントアウトしていないようでした。私はstd :: coutとprintfを使いましたが、printfは "プログラムが動作を停止しました"というエラーを出すようです。どこが間違っていますか?

は、ここでのstd :: coutを持つコードです: -

#include <iostream> 
    #include <cstdio>   
    #include <vector> 
    #include <fstream> 
    using namespace std; 

    int main(){ 
    int np; 
    string temp; 

    scanf("%d", &np); 
    vector <int> money; 
    vector <string> names; 

     for(int i = 0; i< np; i++){ 
      scanf("%s", &temp); 
      names.push_back(temp); 
      cout << names[i] << endl; 
     } 

    return 0; 
    } 

この

は全く任意の文字列が返されませんでした。修正 %schar*を受け入れるため、あなたが std::stringを読み取るため scanfを使用してはならない

printf("%s", &names[i]); 
+0

文字列およびオプションでintを読み込むにはcin <<を使用します。 scanfは動作しません。 %sのchar配列が必要です。 –

+3

私はあなたが良い初心者の本、[ここにいくつかのリストが必要]だと思う(http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)。 –

+1

もし 'scanf("%s "、&temp);' *が**あなたの顔にコンパイラの警告を投げなかったら、警告レベルをよりペタンティックにする必要があるでしょう。 – WhozCraig

答えて

0

:coutのラインが置き換えられ除い

私はprintf関数で試した他のプログラムは、まったく同じです。 std::stringオブジェクトの印刷にはprintf("%s", &names[i]);を使用しないでください。

scanfおよびprintfはC関数である。 C言語にはstd::string型がないため、プレーンなchar配列で動作しています。

代わりのscanfprintfあなたがstd::cinstd::coutを使用する必要があります。

std::string str; 
std::cin >> str; // input str 
std::cout << str; // output str 
0

あなたはすぐに整数を読み取るためにscanf()を使用することはできません。

これは動作するはずです:

int np; 
std::string temp; 

std::cout << "Enter the size: "; 
std::cin >> np; 
//vector <int> money; 
std::vector<std::string> names; 

for (int i = 0; i< np; i++) { 
    std::cin >> temp; 
    names.push_back(temp); 
    std::cout << names[i] << endl; 
} 
+0

'scanf'の整数(C++の方法ではありませんが) – soon

0

あなたのコードについて変更する必要がある2つのものがあります。 まず、のうち、scanf()はC++クラスをサポートしていません。これについてはlinkで詳しく読むことができます。 は、scanf()の代わりにgetline(cin、temp)を使用できます。それを使用するには、cin.ignore();という行を追加する必要があります。を入力する前にgetline呼び出しが行われる前に、数字を入力してEnterキーを押すと、次にgetlineを呼び出すときに使用されるcinバッファーに '\ n'文字が挿入されます。

#include <iostream> 
    #include <cstdio>   
    #include <vector> 
    #include <fstream> 
    using namespace std; 

    int main(){ 
    int np; 
    string temp; 

    scanf("%d", &np); 
    vector <int> money; 
    vector <string> names; 
    cin.ignore(); 
     for(int i = 0; i< np; i++){ 
      getline(cin, temp); 
      names.push_back(temp); 
      cout << names[i] << endl; 
     } 

    return 0; 
    } 

コードhereの作業デモを見てください。

私はそれを正しく説明できたと思います。

+0

ありがとうございます。getlineはstd :: cinを使うよりも効率的ですか? –

+0

あなたのニーズに応じてどちらかを使うことができます。 ** cin **は、スペース、タブ、改行を無視します。ほとんどの場合、ユーザーが入力した不可視文字を文字列に格納する必要があります。その場合、getlineを使用します。詳細については、このリンクを参照してください:http://www.programmingincpp.com/standard-input-function.html –

関連する問題