2014-09-24 90 views
0

我一直在做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; 
} 
+2

將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

+1

你有未定義的行爲。提示 - 'word [i] = str [i]' – 2014-09-24 15:14:52

回答

5
string word; 

是默認構造,其初始化爲空。裏面while循環,你試圖做的事:

word[i] = str[i]; 

這意味着你試圖訪問尚未分配,導致不確定的行爲內存。

嘗試:

word.append(str[i]); 
+2

'word [i] ='\ 0';'也應該刪除。 – Jarod42 2014-09-24 15:17:49

+0

@ Jarod42是的,很好 – taocp 2014-09-24 15:18:30

1

你可以用更簡單的方式來獲得輸入單詞C++。它將幫助您避免將來出現錯誤。

#include <iostream> 
using namespace std; 

int main() 
{ 
    string word; 
    while(cin >> word) 
    { 
     // "word" contains one word of input each time loop loops 
     cout << word << endl; 
    } 
    return 0; 
}