我需要在C ++中使用简单的程序来打开文本文件并逐行查找第二个参数。
文字内容:
1, red
2, blue
3, green
4, orange
所以我需要一个逐行的程序,每行转换成数组(两个元素),然后将第一个元素与用户交互插入的数字进行比较。
因此,如果用户插入2,它逐行进行,比较阵列行的第一个元素,如果匹配,则打印数组中的第二个元素(蓝色),如果用户键入3,则打印绿色...
我一直在用PHP工作,而且比这更容易,所以我现在有点困惑了......:/
答案 0 :(得分:5)
你走了:
#include <iostream>
#include <fstream>
#include <map>
#include <sstream>
int main(int argc, char* argv[]) {
if (argc != 2) {
std::cerr << "Usage: test [inputfile]" << std::endl;
return 1;
}
std::fstream stream(argv[1]);
if (!stream.good()) {
std::cerr << "Error: could not open file: " << argv[1] << std::endl;
return 2;
}
std::string line;
std::map<int, std::string> map;
while (std::getline(stream, line)) {
std::string::size_type pos = line.find(',');
std::stringstream sstream(line.substr(0, pos));
int index;
sstream >> index;
map[index] = line.substr(pos+2);
}
int in;
while (std::cin >> in) {
std::map<int, std::string>::iterator i = map.find(in);
if (i == map.end())
std::cerr << "index not found" << std::endl;
else
std::cout << i->second << std::endl;
}
return 0;
}
答案 1 :(得分:1)
Q1:你如何在C ++中打开文本文件? Q2:你如何逐行阅读文件?
问题3:如何根据该分隔符将带有“,”的字符串转换为数组?
答案 2 :(得分:1)
除了我之外,这可能没有帮助;我开始练习使用Spirit解析(以及karma输出生成作为奖励):
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/std_pair.hpp>
#include <fstream>
#include <map>
namespace qi = ::boost::spirit::qi;
namespace karma = ::boost::spirit::karma;
typedef std::map<int, std::string> index_t;
index_t read_index(const char* filename)
{
using boost::spirit::istream_iterator;
using namespace qi;
index_t result;
std::ifstream ifs(filename);
ifs.unsetf(std::ios::skipws);
istream_iterator begin(ifs), end;
if (!parse(begin, end, (int_ >> omit[lit(',') >> *char_(" \t")] >> *(char_ - eol)) % eol, result))
{
throw std::runtime_error("Unable to read/parse index file ");
}
return result; // http://en.wikipedia.org/wiki/Return_value_optimization
}
int main()
{
index_t index = read_index("input.txt");
using namespace karma;
std::cout << format(('[' << int_ << ": " << *char_ << ']') % eol, index) << std::endl;
for (int i=0; i<10; i++)
{
int lookup=rand()%6;
std::cout << "Random lookup: " << lookup << ": " << index[lookup] << std::endl;
}
return 0;
}
哦,示例输出:
[1: red]
[2: blue]
[3: green]
[4: orange]
Random lookup: 1: red
Random lookup: 4: orange
Random lookup: 3: green
Random lookup: 1: red
Random lookup: 5:
Random lookup: 1: red
Random lookup: 4: orange
Random lookup: 0:
Random lookup: 3: green
Random lookup: 1: red