2017-01-31 10 views
0
#include "stdafx.h" 
#include <iostream> 
#include <string> 
#include <algorithm> 
using namespace std; 

string output; 
string words; 
int i; 

int main() 
{ 
    cin >> words; // gets words from user 
    output = ""; // readys the output string 
    i = 0;  // warms up the calculator 
    int size = words.size(); // size matters 
    while (i <= size) { // loops through each character in "words"  (can't increment in the function?) 
     output += ":regional_indicator_" + words[i] +':'; //  appends output with each letter from words plus a suffix and prefix 
     ++i; 
    }    

    cout << output << endl; // prints the output 
    return 0; 
} 

私はこのコードを意図していますが、私は思っています。単純に文を取って、すべての文字をその文字+接尾辞と接頭辞に置き換えます。 私の問題は、デバッガで実行すると、私は"hello world"を入力し、プログラムは"osss"を出力するということです。ランダムな文字を出力する文字列変更プログラム

私はC++で全く教育を受けておらず、ここでは完全に喪失しています。それは私の++iですか?

+0

'cinを>>言葉;'、1つの単語だけではなく、ライン内のすべての単語を読み込みます。 – Barmar

+0

'+'を使って文字列リテラルと文字を連結することはできません。引数の1つは 'std :: string'でなければなりません。 – Barmar

答えて

0

このライン:

output += ":regional_indicator_" + words[i] +':'; //  appends output with each letter from words plus a suffix and prefix 

は動作しません。文字列連結のための+演算子のオーバーロードは、引数の1つがstd::stringである場合にのみ機能します。しかし、あなたはそれをC文字列のリテラルとcharで使用しようとしています。それを変更します。

output += "regional_indicator_"; 
output += words[i]; 
output += ':'; 

これは、各パートのstd::string+=オーバーロードを使用し、何をしたいん。

また、あなたが全体のラインを読みたい場合は、だけではなく、単一の単語、使用:

getline(cin, words); 
+0

ありがとう!完璧に動作し、スペースを処理するためにその周りにifループを投げました。私は今夜​​KerninghanとRitchieを読み始めますので、私はもっと愚かな質問をする必要はありません。 – rockcabbage

関連する問題