为什么将字符串向量值转换为 cstring 不等同于手动写入字符串?
Why isn't a string vector value converted to cstring the equivalent of manually writing the string?
i有一个输入文件,该文件包含一个.txt文件列表中的文件夹中。我可以循环浏览输入文件,然后将.txt文件文件ply放在字符串向量中。但是,当我尝试使用sections
向量中的一个filepath打开另一个ifstream(字符串向量值转换为cstring)时,
std::ifstream secFile(sections[i].c_str());
行secFile.fail()
返回真实的含义,含义失败。如果我使用当前评论的线,该线硬编码是filepath(手动编写字符串),而不是从向量中获取
//std::ifstream secFile("test2/main0.txt");
它不再失败。我什至尝试将sections[0].c_str()
和"test2/main0.txt"
输出到文本文件中,每个文本的文本完全相同。我什至比较了文本文件的十六进制值,并且没有看不见的字符可能引起这样的问题。
知道问题可能是什么?
这是我的代码:
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cstring>
//using namespace std;
int main (int argc, char* argv[]){
if(argc != 2){
return(0);
}
std::vector<std::string> sections;
std::vector<std::string> overlaps;
std::ifstream file(argv[1]);
std::string str;
std::string secLine;
std::string overlapLine;
std::string strLow;
std::string wholePage = "";
//determine if input text file is overlap text or main text
while (getline(file, str))
{
if (str.find("overlap")!=-1){
overlaps.push_back(str);
}
else{
sections.push_back(str);
}
}
file.clear();
for(int i = 0; i < sections.size();i++){
//HERE IS MY QUESTION
std::ifstream secFile(sections[i].c_str());
//std::ifstream secFile("test2/main0.txt");
if(secFile.good()){
std::cout << "ngood4n";
}
if(secFile.bad()){
std::cout << "bad4n";
}
if(secFile.fail()){
std::cout << "fail4n";
}
if(secFile.eof()){
std::cout << "eof4n";
}
int secLength = 0;
//determine number of files in test2/
while (getline(secFile,secLine)){
secLength++;
}
secfile.clear();
secfile.seekg(0);
int j = 0;
while (getline(secFile,secLine)){
if (i == 0 && j==0){
wholePage += std::string(secLine) + "n";
}
else if(j==0){
//do nothing
}
else if(i == (sections.size()-1) && j == secLength){
wholePage += std::string(secLine) + "n";
}
else if(j == secLength){
//do nothing
}
else{
wholePage += std::string(secLine) + "n";
}
j++;
}
int k = 0;
if(i < sections.size()-1){
std::ifstream overFile(overlaps[i].c_str());
int overLength = 0;
while (getline(overFile,overlapLine)){
overLength++;
}
while (getline(overFile,overlapLine)){
std::cout << "Hi5";
if(k == 0){
//do nothing
}
else if(k == overLength){
//do nothing
}
else{
if (wholePage.find(overlapLine)){
//do nothing
}
else{
wholePage += std::string(secLine) + "n";
}
}
}
k++;
}
}
std::ofstream out("output.txt");
out << wholePage;
out.close();
std::cout << "n";
return 0;
}
您还没有提供足够的信息以确保,但最可能的问题是空格。getline
不会从其产生的线条上剥离尾随的空格,因此您可能正在尝试打开一个名为"test2/main0.txt "
(尾随空间)的文件,该文件与"test2/main0.txt"
不同。在大多数情况下,您需要在将字符串存储到vector
之前修剪尾随。由于某些空间在法律上可以成为文件名的一部分,因此真正的解决方案是确保不存在垃圾whitespace,但是Tailting Whitespace是文件名很少,您可以希望文件名不使用它。/p>
在这里您要通过一个文件名:
std::ifstream secFile("test2/main0.txt");
在这里,您正在传递文件线:
std::ifstream secFile(sections[i].c_str());
ifstream期望文件名,而不是文件中的文本行。之所以失败,是因为您要输入的文本不代表您要打开的文件。