2013-03-03 9 views
5
#include <iostream> 
#include <string> 
#include <vector> 

/* 
    Using STL's string class because the problem does not refer any 
    limits regarding the number of characters per line. 
*/ 

using namespace std; 

int main() 
{ 
    string line; 
    vector<string> lines; 
    while (getline(cin, line)) 
    { 
    lines.push_back(line); 
    } 

    unsigned int i, u; 
    unsigned int opening = 1; // 2 if last was opening, 1 if it was closing 
    for (i = 0; i < (int) lines.size(); i++) 
    { 
    for (u = 0; u < (int) lines[u].length(); u++) 
    { 

    } 
    } 

    return 0; 
} 

że mam prosty kod, który tylko czyta w ciągu kilku liniach (plik wejściowy):STL String :: długość() SEGFAULTing

"To be or not to be," quoth the Bard, "that 
is the question". 
The programming contestant replied: "I must disagree. 
To `C' or not to `C', that is The Question!" 

Uważam jednak, że jest SEGFAULTing jak to czyta „” (spacja) znak w pierwszym wierszu (4 znaków):

(gdb) run < texquotes_input.txt 
Starting program: /home/david/src/oni/texquotes < texquotes_input.txt 

Program received signal SIGSEGV, Segmentation fault. 
0x00007ffff7b92533 in std::string::length() const() from /usr/lib/x86_64-linux-gnu/libstdc++.so.6 

naprawdę nie mogę zrozumieć, dlaczego nie robię niczego wewnątrz pętli, jestem po prostu zapętlenie.

+2

Excellent „mała pełna Przykład kompilacji ". –

+0

Zasada kciuka: jeśli w stdlib występuje segfault, prawdopodobnie czytasz/piszesz/usuwasz, gdzie nie powinieneś;). –

Odpowiedz

6

Już znalazłem problem. To wewnętrzna pętla:

for (u = 0; u < (int) lines[u].length(); u++) 
{ 

} 

Powinno być:

for (u = 0; u < (int) lines[i].length(); u++) 
{ 

} 
2

W innym odpowiedzieć na typo indeks został już zauważony.

Chciałbym dodać, że za pomocą zakres oparte for pętle tego rodzaju problemy są trudniejsze tak się stało, ponieważ pętla jest trochę bardziej „ukryte”:

#include <iostream> 
#include <string> 
#include <vector> 
using namespace std; 

int main() 
{ 
    string line; 
    vector<string> lines; 
    while (getline(cin, line)) 
    { 
    lines.push_back(line); 
    } 

    for (const auto& currLine : lines) 
    { 
    for (auto ch : currLine) 
    { 
     cout << ch; 
    } 
    cout << '\n'; 
    } 
} 
+0

Wielka wskazówka, dzięki! –

+0

Nie ma za co. –