Skip to content

Instantly share code, notes, and snippets.

@stoensin
Last active June 30, 2021 12:05
Show Gist options
  • Save stoensin/8e23297c864e98845817e19cb6727b0a to your computer and use it in GitHub Desktop.
Save stoensin/8e23297c864e98845817e19cb6727b0a to your computer and use it in GitHub Desktop.
getline(cin, inputLine);函数,接受一个字符串的输入包含空格,遇到回车停止要包含 #incldue<string> ,一般用来读取用string类存储表示的字符串。 很多程序中,可能会碰到ofstream out("Hello.txt"), ifstream in("..."),fstream foi("...")这样的的使用,并没有显式的去调用open()函数就进行文件的操作,直接调用了其默认的打开方式,因为在stream类的构造函数中调用了open()函数,并拥有同样的构造函数,所以在这里可以直接使用流对象进行文件的操作
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
// 读取文件 文件每一行是空格分隔开的图片像素值 每行1000个值
int main()
{
ifstream infile_feat(loadFeatList); //加载数据文件路径,获取到流对象infile_feat
string feature; //存储读取的每行数据
float feat_onePoint; //存储每行按空格分开的每一个float数据
vector<float> lines; //存储每行数据
vector<vector<float>> lines_feat; //存储所有数据
lines_feat.clear();
while (!infile_feat.eof()) { //从流对象eof之前的数据中遍历
getline(infile_feat, feature); //一次读取一行数据
stringstream stringin(feature); //使用串流实现对string的输入输出操作
lines.clear();
while (stringin >> feat_onePoint) { //按空格一次读取一个数据存入feat_onePoint
lines.push_back(feat_onePoint); //存储每行按空格分开的数据
}
lines_feat.push_back(lines); //存储所有数据
}
infile_feat.close();
return 0;
}
// 其他办法 推荐方法3
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
string str = "dog cat cat dog";
istringstream in(str);
vector<string> v;
// Method 1
string t;
while (in >> t) {
v.push_back(t);
}
// Method 2
// #include <iterator>
copy(istream_iterator<string>(in), istream_iterator<string>(), back_inserter(v));
// Method 3, recommend
string t;
while (getline(in, t, ' ')) {
v.push_back(t);
}
// Method 4
string str2 = str;
while (str2.find(" ") != string::npos) {
int found = str2.find(" ");
v.push_back(str2.substr(0, found));
str2 = str2.substr(found + 1);
}
v.push_back(str2);
// Method 5
// #include <stdio.h>
// #include <stdlib.h>
// #include <string.h>
char *dup = strdup(str.c_str());
char *token = strtok(dup, " ");
while (token != NULL) {
v.push_back(string(token));
token = strtok(NULL, " ");
}
free(dup);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment