【发布时间】:2016-03-02 19:15:59
【问题描述】:
我有一些我无法弄清楚的奇怪问题。当我运行下面的代码时,它需要 file.txt 将其逐行读取到 vector<string> 中,然后将每个索引与字符串 "--" 进行比较,它不会进入比较阶段。
此外,在 for 循环字符串 m 下的 convert_file() 中,有一些奇怪的行为:string m = "1"; m+= "--"; ('--' inside vector) m+= "2"; 将打印到控制台 2--;这让我觉得有些东西正在破坏向量。 2 正在替换第一个字符 1。这使它看起来像向量被窃听了。
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
vector<string> get_file(const char* file){
int SIZE=256, ln=0;
char str[SIZE];
vector<string> strs;
ifstream in(file, ios::in);
if(!in){
return strs;
} else {
while(in.getline(str,SIZE)){
strs.push_back(string(str));
ln++;
}
}
in.close();
return strs;
}
void convert_file(const char* file){
vector<string> s = get_file(file);
vector<string> d;
int a, b;
bool t = false;
string comp = "--";
for(int i=0; i<s.size(); i++){
string m = "1";
m+= string(s.at(i));
m+= "2";
cout << m << endl;
if(s.at(i) == comp){
cout << "s[i] == '--'" << endl;
}
}
}
int main(){
convert_file("test.txt");
return 0;
}
现在当我运行一个测试文件来检查一个类似的程序时:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(){
vector<string> s;
s.push_back("--");
s.push_back("a");
for(int i=0; i<s.size(); i++){
cout << "1" << s.at(i) << "2" << endl;
if(s.at(i) == "--"){
cout << i << "= --" << endl;
}
}
return 0;
}
打印出1--2、0= --、1a2。它可以正常工作,可以正确打印并进行比较。这使我认为当我将线拉成字符串时正在发生一些事情。
Windows 7, cygwin64
g++ version 4.9.3
compile: D:\projects\test>g++ -o a -std=c++11 test.cpp
【问题讨论】:
-
你能添加你的主程序和第一个程序的文件吗?
-
我敢打赌该文件包含
"\n\r"行结束序列。也就是说,临时的实际上看起来像"1\r--2"。我会使用prog | od -c查看输出,看看实际有什么。 -
@Gernot1976:
getline()吞下'\n'字符(不过get()保留了它们)。 -
该程序对我来说运行良好。我会调查@DietmarKühl 指出的
\r\n问题。 -
运行程序“测试”输出:“2--”、“2a-”。 '测试程序 | od -c' 输出:'0000000 1 - - \r 2 \n 1 a - \r 2 \n','0000014'。所以字符串中有\n和\r