我有一些我无法弄清楚的奇怪问题。当我运行下面的代码时需要 file.txt
逐行读入 vector<string>
然后将每个索引与字符串 "--"
进行比较它没有进入比较阶段。
此外,在 for 循环字符串 m 下的 convert_file() 中,有一些奇怪的行为:string m = "1"; m+= "--";
('--' 内部 vector )m+= "2";
将打印到控制台 2--
;这让我觉得有些东西正在窃听 vector 。 2 正在替换第一个字符 1。这使得它看起来像 vector 被窃听了。
#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
最佳答案
根据行为和讨论,文件中的行使用 "\r\n"
序列终止。处理剩余的 '\r'
最简单的方法是在读取一行后将其删除。例如:
for (std::string line; std::getline(file, line); ) {
if (!line.empty() && line.back() == '\r') {
line.resize(line.size() - 1u);
}
strs.push_back(line);
}
如果您坚持读入char
数组,您可以使用file.gcount()
来确定读取的字符数以快速找到字符串的结尾。但是请注意,该数字包含 bewline 字符,即您要检查 str[file.gcount() - 2]
并可能将其设置为 '\0'
(当然,如果计数大于或等于 2)。
关于c++ - std::vector<string> 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33976814/