我试图读取存储在由逗号分隔的同一行上的两个double值,从文本文件或csv文件到矢量。数字以这种格式存储,如[1688.37,115.14]。我想从文件中读取这些数字,然后存储在数组中,这样就可以访问第一个和第二个数字。我的代码编译但不会显示数字。这里是C ++中的代码。
ifstream file("C:/arrow1.txt",ios::app);
double s;
std::vector<double> data;
while(file>>s){
data.push_back(s);
}
for(int i=0; i<data.size(); i++){
std::cout<<data[i]<<std::endl;
}
此代码读取并显示数字,但与字符串在同一行。然后我不知道如何访问第一个和第二个数字
ifstream fh("C:/arrow1.csv",ios::app);
std::vector<std::string> vs;
std::string s;
while(fh>>s){
vs.push_back(s);
}
for(int i=0; i<vs.size(); i++){
std::cout<<vs[i]<<std::endl;
}
任何帮助?
答案 0 :(得分:1)
您可以将第二次尝试与atof()
(Have a look here)结合使用。它会将string
转换为double
。
将第一个数字复制到第二个字符串中,然后使用atof()
获取双倍值。
示例:
// Your copied values from the file
std::string s1 = "[1688.37,";
std::string s2 = "115.14]";
// Copy the number without "[" and ",", the length of the number is variable
std::string str1 = s1.substr(1, s1.length()-1); // Copy the first number in str1
double firstNum = atof(str1.c_str());
cout << firstNum << endl;
// Copy the second number without "]"
std::string str2 = s2.substr(0, s2.length()-1); // Copy the second number in str2
double secondNum = atof(str2.c_str());
cout << secondNum << endl;
答案 1 :(得分:1)
如果以下示例中声明为istream
的{{1}}(是stringstream
,ifstream
)包含格式为任意数量的行的明确定义模式s
- 您可以在流上使用[float1, float2]
运算符(本例中为流提取运算符)来读取值,并使用>>
调用来阅读get
,{{ 1}},,
和[
字符,如下例所示:
]