2015-09-25 2 views
-1

В настоящее время я пытаюсь создать программу, которая читает в файле, просматривает этот файл и выводит все слова в этом файле, окруженные «отметками». В настоящее время я в тупике и надеялся получить ! некоторую помощьБесконечный пока цикл и получение неверного вывода

#include <iostream> 
// For file I/O: 
#include <fstream> 
#include <cstdlib> 
#include <iomanip> 

using namespace std; 

// Prototype the count function so we can have it below it's first 
// use in main(). 
void count(istream& in, int& lines, int& words, int& characters); 
/* 
* wc <filename> 
    */ 

int main(int argc, char *argv[]) 
{ 
if (argc < 2) { 
    cerr << "Usage: wc <filename>" << endl; 
    return 0; 
} 
// Open the file specified by argv[1] for reading: 
    // Constructs a ifstream object called "in": 
    ifstream in(argv[1]); 
    // Was there a problem opening the file? 
    if (!in.good()) { 
    cerr << "Unable to open file [" << argv[1] << "] for reading." << endl; 
    return 1; 
    } 

    int lines = 0, words = 0, characters = 0; 
    count(in, lines, words, characters); 
    cout << setw(5) << lines << " " << words << " " << 
    characters << " " <<   argv[1] << endl; 

    // Close the input stream: 
    in.close(); 
    } 

    void count(istream& in, int& lines, int& words, int& characters) 
    { 
    int i; 
    char s; 
    int ch; 
    bool inword = false; 

    // Read until the end of file is reached, or there was an error: 
    while (!in.eof()) { 
    // Read a character from the input stream "in": 
    s = in.get(); //Set char s = in.get 
    for(i=0; s != 0; i++){ //Loop to iterate through the characters 
     while(s == '"'){ //While s is equal " 
     cout << s << endl; // Print s 
     if(s == '"') // If we hit another ", then we break 
     break; 
     } 
    } 
    if (in.good() == false) return; 
    characters++; 
    if (!isspace(ch) && !inword) { 
    inword = true; 
    words++; 
    } else if (isspace(ch) && inword) { 
    inword = false; 
    } 
    if (ch == '\n') lines++; 
    } 
    } 

ответ

0

ваш алгоритм кажется неправильным .. в цикл вы сравните с «s», но вы не обновляя его ... попробовать что-то вроде этого в главном цикле (КНИ):

while (!in.eof() && (s = in.get()) != '"'); // read to first quote char 
/* this is the word we want.. run to end quote marks.. */ 
while (!in.eof() && (s = in.get()) != '"') { 
    cout << s; 
} 
cout << endl; 
+0

Я сделал это, но, похоже, я все еще бесконечно зацикливаюсь. Он также ничего не печатает, кажется, что это просто cout -end endl. – Frebadyia

+0

Игнорировать этот последний комментарий, я понял, почему он бесконечно зацикливается. Теперь я получаю seg-ошибки. Любые комментарии о том, почему это может быть? – Frebadyia

+0

использовать gdb возможно? – Karthik

 Смежные вопросы

  • Нет связанных вопросов^_^