我必须比较单词文件中的两列,这两列逐行填充数字。例如,如果有一个单词文件有以下两列:
1 56
2 57
3 59
4 63
然后,如果我给出输入2,那么在C C++中输出应该是57。什么逻辑有助于映射表并使用其值?请帮忙。到目前为止,我想不出任何办法。我正在使用这段代码逐行读取文件。
#include <stdio.h>
int main(int argc, char* argv[])
{
char const* const fileName = argv[1]; /* should check that argc > 1 */
FILE* file = fopen("C:\Users\parth\Downloads\state_model_files.txt", "r"); /* should check the result */
char line[256];
while (fgets(line, sizeof(line), file)) {
/* note that fgets don't strip the terminating n, checking its
presence would allow to handle lines longer that sizeof(line) */
printf("%s", line);
}
/* may check feof here to make a difference between eof and io failure -- network
timeout for instance */
fclose(file);
getchar();
return 0;
}
基本上,您想要做的是(1)打开文件,(2)从文件中获取一行,(3)将每列的值写入某个变量,(4)将它们存储到映射中。稍后,您可以进行类似您在帖子中建议的查询。请注意,下面的方法对您的输入数据进行了某些假设。
#include <iostream>
#include <sstream>
#include <fstream>
#include <map>
using namespace std;
int main(int argc, char *argv[]) {
ifstream in(argv[1]);
if(!in) {
cout << "Could not open file " << argv[1] << endl;
return -1;
}
map<int, int> m;
int c1, c2;
string fields;
while(getline(in, fields)) {
istringstream ss(fields);
ss >> c1 >> c2;
m[c1] = c2;
}
in.close();
return 0;
}