代码
void test() { vector<string> words; string s; char ch[1024]; ifstream infile("text.txt", ios::in); ofstream ofile("sentence.txt", ios::out); if (ofile) { // 按行读入 while (infile.getline(ch, 1024)) { cout << ch << endl; ofile << ch << endl; } infile.close(); ofile.close(); } infile.open("text.txt", ios::in); ofile.open("words.txt", ios::out); if (ofile) { // 按单词读入(遇到空格、换行、制表符等都会视为一个单词的结束) while (infile >> s) { cout << s << endl; ofile << s << endl; } infile.close(); ofile.close(); } }代码
void test() { vector<string> words; string s; char ch[1024]; ifstream infile("contact.txt", ios::in); unordered_map<string, vector<int>> infos; while (getline(infile, s)) { string key; vector<int> vec; int tmp = 0; istringstream is(s); is >> key; // 构造一个包含字符串的读入缓冲区,然后可以从这个缓冲区中读取所需要的信息 while (is >> tmp) { vec.push_back(tmp); } infos[key] = vec; cout << s << endl; } cout << "=====infos======" << endl; ostringstream os; for (auto it = infos.begin(); it != infos.end(); it++) { os << "key is : " << it->first << ", value is : "; for (auto & num : it->second) os << num << " "; cout << os.str() << endl; os.str(""); //os.clear(); //这句话只是清空缓冲区的标志位,并没有清空缓冲区的内容 } }contact中的内容
AA 1 4 7 BB 2 5 8 CC 3 6 9