将字符串放入向量中会产生空字符串

时间:2013-12-19 14:30:19

标签: c++ visual-c++

这是我的代码部分:

#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);
        }
    }

问题发生在

words.insert(words.end,word)

word

包含我文件中的单词,矢量项

words[i]

包含一个空字符串。

这怎么可能?

1 个答案:

答案 0 :(得分:12)

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

那永远无法奏效。 c_str()是指向字符串当前内容的const指针,您不能修改它。即使你确实颠覆const(使用强制转换,或者在这种情况下,使用令人讨厌的C风格的可变参数函数),写入超出该内存的末尾也不会改变字符串的长度 - 它只会给出未定义的行为。

为什么不使用C ++样式的I / O,读入string以便它自动增长到正确的大小?

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);
    }
}
相关问题