0

Here's part my code:

#include <stdio.h>
#include<string>
#include<string.h>
#include<algorithm>
#include <vector>
#include <iostream>
using namespace std;

int main(){
    FILE *in=fopen("C.in","r");
    //freopen("C.out","w",stdout);
    int maxl=0;
    int i;
    string word;
    vector<string> words;
    while(!feof(in)){
        fscanf(in,"%s ",word.c_str());
        int t=strlen(word.c_str());
        if(t>maxl){
            maxl=t;
            words.clear();
            words.insert(words.end(),word);
        }else if (t==maxl){
            words.insert(words.end(),word);
        }
    }

the problem occurs at

words.insert(words.end,word)

while

word

contains the word from my file, the vector item

words[i]

contains an empty string.

How is this possible?

  • 2
    Please show all your variable declarations! – OldProgrammer Dec 19 '13 at 14:33
  • 2
    word.c_str() returns `const char*`, so you shouldn't modify it. – hetepeperfan Dec 19 '13 at 14:34
  • [`while (!eof())` is wrong.](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – chris Dec 19 '13 at 14:37
  • 1
    Mike's given you the final answer, but it's probably worth pointing out that `while ( !feof( in ) )` is no better than `while ( !in.eof() )`. Neither tell you whether the following input will succeed or not. – James Kanze Dec 19 '13 at 14:38

1 Answers1

11
fscanf(in,"%s ",word.c_str());

That's never going to work. c_str() is a const pointer to the string's current contents, which you mustn't modify. Even if you do subvert const (using a cast or, in this case, a nasty C-style variadic function), writing beyond the end of that memory won't change the length of the string - it will just give undefined behaviour.

Why not use C++ style I/O, reading into a string so that it automatically grows to the correct size?

std::ifstream in(filename);
std::string word;
while (in >> word) {
    if (word.size() > maxl) {
        maxl = word.size();
        words.clear();
        words.push_back(word);
    } else if (word.size() == maxl) {
        words.push_back(word);
    }
}
Mike Seymour
  • 235,407
  • 25
  • 414
  • 617
  • And indeed, subverting the `const` pointer yielded by `c_str()` and writing to it will yield UB even if you don't write beyond the end of the buffer. – John Dibling Dec 19 '13 at 14:53
  • @JohnDibling: Indeed. I'm just mentioning the part that's most likely to cause catastrophic behaviour. – Mike Seymour Dec 19 '13 at 14:54