2013-12-19 136 views
0

这里是部分我的代码:把字符串转换为矢量赋予空字符串

#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 

包含我的文件,矢量字item

words[i] 

包含一个空字符串。

这怎么可能?

+2

请显示您所有的变量声明! – OldProgrammer

+2

word.c_str()返回'const char *',所以你不应该修改它。 – hetepeperfan

+0

['while(!eof())'wrong。](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – chris

回答

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); 
    } 
} 
+0

事实上,即使你没有写入超过缓冲区的末尾,颠覆“c_str()”产生的'const'指针并写入它也会产生UB。 –

+0

@JohnDibling:的确如此。我只是提到最可能导致灾难性行为的部分。 –

相关问题