我正在尝试将文本文件读成对的向量。该文本文件包含以下内容: 第一行告诉我们有多少个字符串。第二行是一个int,告诉第一个字符串中有多少个字符。然后,第三行包含字符串本身。之后,接下来是“模式”(再次使用int有多少个字符,然后是字符串本身)。 例如:
我的想法是,分别阅读第一行(工作正常)。然后为每个int和string创建对。第二部分,不知何故,不起作用,所以如果有人能帮我找到错误,我真的很感激。
所以这是我的代码:
#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <utility>
using namespace std;
int main(int argc, char *argv[])
{
if (argv[1])
{some code here...}
// arg[2] is formatted in some manner of the example above
if (argv[2])
{
//Declare Variables:
string buffer;
string temporary;
vector <pair <int, string> > patVec;
pair <int, string> patPair;
// Ifstream first txt File = (argv[2]
ifstream ifile2(argv[2]);
// Get first line and store in variable number of Patterns --> This works fine
getline(ifile2, temporary);
int numberOfPatterns = atoi(temporary.c_str());
// Process rest of file
int i;
for (patVec[i=0]; i <= numberOfPatterns - 1; i++)
{
getline(ifile2, buffer);
stringstream strs(buffer);
// Fill up the Vector with pairs
strs >> patPair.first;
strs >> patPair.second;
patVec.push_back(patPair);
}
}
}
//Declare Variables
string buffer;
string temporary;
vector <pair <int, string> > patVec;
pair <int, string> patPair;
int plength;
string pCharacters;
// Get first line and store in variable number of Patterns
getline(ifile2, temporary);
int numberOfPatterns = atoi(temporary.c_str());
cout << "The number of Patterns is " << numberOfPatterns << endl;
// Process rest of file
for (int i=0; i <= numberOfPatterns - 1; i++)
{
// stringstream strs(buffer);
// Fill up the Vector with pairs
getline(ifile2, buffer);
stringstream int_reader(buffer);
int_reader >> plength;
getline(ifile2, buffer);
stringstream str_reader(buffer);
str_reader >> pCharacters;
patPair = make_pair (plength, pCharacters);
patVec.push_back(patPair);
cout << "length of pattern " << i << " is " << plength << endl;
cout << " characters are: " << pCharacters << endl;
}
ifile2.close();
}
答案 0 :(得分:0)
这是一个更正的程序。它仍然存在一些问题,例如:
变量的预先声明。
该对没有typedef。
但似乎效果很好。
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdlib>
int main(int argc, char * argv[])
{
//Declare Variables:
std::string buffer;
std::string temporary;
std::vector <std::pair <int, std::string> > patVec;
std::pair <int, std::string> patPair;
// Ifstream first txt File = (argv[2]
std::ifstream ifile2((const char *)(argv[2]));
// Get first line and store in variable number of Patterns --> This works fine
getline(ifile2, temporary);
int numberOfPatterns = atoi(temporary.c_str());
// Process rest of file
for (int i = 0 ; i <= numberOfPatterns - 1; i++)
{
getline(ifile2, buffer);
std::stringstream int_reader(buffer);
// Fill up the Vector with pairs
int_reader >> patPair.first;
getline(ifile2, buffer);
std::stringstream str_reader(buffer);
str_reader >> patPair.second;
patVec.push_back(patPair);
}
return 0;
}