我一直在做coderbyte編程挑戰,並在做一個,遇到問題。我想從字符串中分離一個單詞,對它進行一些檢查,然後移動到另一個單詞。我要發佈的代碼應該只顯示第一個單詞並將其打印在屏幕上。當我運行它時,它不會打印任何東西。我認爲,也許我在while循環中做了錯誤的事情,所以我做了一個簡單的測試。假設我的輸入是「This is a test sentence」,而不是單詞(在cout中),我輸入word [0]。然後打印「T」就好了。你能找到問題所在嗎?字符串將不會打印
#include <iostream>
#include <string>
using namespace std;
int Letters(string str) {
int i=0;
int len=str.length();
string word;
while(i<len){
if(isspace(str[i])){word[i]='\0'; break;}
word[i]=str[i];
i++;
}
cout<<word;
return 0;
}
int main() {
int test;
string str;
getline(cin, str);
test=Letters(str);
return 0;
}
將word [i] = str [i];改爲['word.append(str [i]);'](http://en.cppreference.com/w/cpp/string/basic_string的/附加)。你沒有保留'word'的空間,所以你不能訪問'word [i]'。 – 2014-09-24 15:14:50
你有未定義的行爲。提示 - 'word [i] = str [i]' – 2014-09-24 15:14:52