表格内容如图所示:
直接按照之前方法,选择打开 xlsx/xls 文件会出现乱码:
Way I 使用 txt 格式
在 Excel 中另存为 txt 文件。
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <conio.h>
using namespace std;
int main(int argc, char* argv[])
{
string infile = "test_2.txt";
vector<string> vec_str;
ifstream input(infile);
if (input) // ensure that the input is seccessful
{
string word;
while (input >> word)
{
vec_str.push_back(word);
}
}
else
{
cerr << "Cannot open file " << infile << "." << endl;
}
input.close();
for (const auto& c : vec_str)
{
cout << c << endl;
}
return 0;
}
Output:
Way III 用 csv 格式
在 Excel 中另存为 csv 文件。
然后发现很麻烦的是中间是逗号隔开!!!
也就是:
Learning,C++
is,fun!
所以代码就比较复杂。
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <conio.h>
using namespace std;
constexpr int MAX_LENGTH = 1024;
int main(int argc, char* argv[])
{
string infile = "test_2.csv";
vector<string> vec_str;
ifstream input(infile);
if (input) // ensure that the input is seccessful
{
string line_str;
while (getline(input, line_str)) // get the whole line
{
string word = "";
for (int i = 0; i != line_str.size(); i++)
{
if (line_str[i] != ',') // if it is ',' go to next word
{
word += line_str[i]; // store the word
}
else
{
vec_str.push_back(word);
word = "";
}
}
vec_str.push_back(word);
}
}
else
{
cerr << "Cannot open file " << infile << "." << endl;
}
input.close();
for (const auto& c : vec_str)
{
cout << c << endl;
}
return 0;
}
Output:
ALL RIGHTS RESERVED © 2020 Teddy van Jerry
欢迎转载,转载请注明出处。