如何修复向量不从文件打印值
How to fix vector not printing values from file
我试图从文本文件中逐行获取一些值:
17.09 284.60 486.01 34.12 12.04 1.20 2.33 36.85 73.44
31.25 196.09 323.26 69.76 47.33 79.82 11.42 27.97 66.61
28.76 41.45 992.29 1.29 42.33 10.83 19.16 5.86 1.88
取这些值并将其放入向量。每行都有在计算中使用的值。
我的代码:
#include <iostream>
#include <fstream>
#include <string>
#include <iterator>
#include <vector>
using namespace std;
int main() {
ifstream xfile;
string input;
double num=0;
int count = 0;
vector <double> myvector;
cout << "Input the file: ";
cin >> input;
xfile.open(input);
if (xfile.is_open()) {
cout << "File accessed!" << endl;
while (getline(xfile, input)) {
count++;
myvector.push_back(num);
}
}
else {
cout << "File opening failed!"<<endl;
}
cout << "Numbers of lines in the file : " << count << endl;
for (int i = 0; i < myvector.size(); i++) {
cout << myvector[i] << "t";
}
cin.fail();
return 0;
}
我的输出有些正确,只是它仅打印出零:https://ibb.co/xqwt1hr
编辑:输入是用于文件的名称。" ahu_long.txt"
您从未使用过num
变量。
double num=0;
....
....
size_t pos = 0;
std::string token;
while (getline(xfile, input)) {
count++;
// you need convert your "input" to a double and save it to "num"
while ((pos = input.find(" ")) != std::string::npos) {
token = input.substr(0, pos);
// std::cout << token << std::endl;
num = atof(token.c_str());
myvector.push_back(num);
input.erase(0, pos + delimiter.length());
}
}
用文件从文件中更改变量。
相关文章:
- 使用 getline 从输入文件打印时如何忽略空白行
- C++击球平均值程序使用输入/输出文件打印名称,平均值,最高/最低平均值时遇到麻烦
- 了解文件输入和输出,我可以写入文件,但无法从文件打印
- 如何将文件打印到其他文件夹
- 如何修复向量不从文件打印值
- 从文本文件打印后如何摆脱新线条,并在打印时摆脱结局空间
- 使用数组从文件打印整数
- 从文本文件打印 sfml 中的 2D 数组
- 从输入文件打印图形
- 从C 中的.txt文件打印出所选的数据
- 超载Ostream运算符从文件打印矩阵
- 为什么这不从TXT文件打印值
- 从文本文件打印字符串和整数 (C++)
- 为什么它只打印文本文件的一个单词,而不是将整个文本文件打印到html文件中
- C++从文本文件打印回文
- 无法从文件打印文本
- 尝试从输入文件打印,但打印最后一个输入两次
- 在 c++ 中从文件打印 2D 数组
- 从 postgresql 上运行的 c++ 文件打印
- 获取字符串从文本文件打印随机行时出现问题