c++ - 用虚拟数据填充二维数组和输入表单 txt 文件不起作用
问题描述
嗨,所以我需要用 txt 文件中的值填充像 x 这样的虚拟值的二维数组,如果 file.txt 的数据很少或没有数据,则“x”是用来填充空列的
1 23 3 42 5 63 4 . 5
-2 1 43 95 55 5 43 2 -6
. 2 3 -4 5 43 -4 4 35
82 61 3 5 -5 65 . 2 6
我的C++看起来像这样
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int main(){
ifstream file;
ofstream newfile;
string filename;
string text;
const int n = 10;
char x = 'x';
double A[n][n];
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
A[i][j] = x;
cout << A[i][j];
}
}
do{
cout << "Podaj nazwe pliku(wraz z rozszerzeniem): ";
cin >> filename;
file.open(filename.c_str());
}while (!file.is_open());
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
if (!file.eof()){
getline(file, text);
A[i][j] = stod(text, 0);
}else{
break;
}
}
}
file.close();
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
cout << A[i][j];
}
cout << endl;
}
}
当我打印出这个数组时,我得到像 127.77098e-3184 这样的输出我无法复制我的输入,因为它现在没有打印我不知道为什么
解决方案
问题:
- 当你使用时,
std::getline
你取整行而不是取一个数字。 "."
不是一个有效的参数,std::stod
所以它会抛出一个std::invalid_argument
异常。
解决方案:
- 改为使用
std::ifstream::operator>>
。 - 重新格式化文件并将 更改为
"."
它应该表示的值(我猜它是 0)。即使在语义上,一个点本身也不代表一个数字。
附加信息:
using namespace std;
被认为是一种不好的做法。- 该
newFile
变量未使用。 x
变量应该是双精度的。- 标
<cmath>
头未使用。 - 您可以使用
std::array
.
完整代码:
文件.txt
1 23 3 42 5 63 4 0 5
-2 1 43 95 55 5 43 2 -6
0 2 3 -4 5 43 -4 4 35
82 61 3 5 -5 65 0 2 6
主文件
#include <iostream>
#include <fstream>
int main(){
std::string filename;
std::string text;
constexpr int n = 10;
double x = -1;
double A[n][n];
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
A[i][j] = x;
std::cout << A[i][j] << " ";
}
std::cout << std::endl;
}
std::ifstream file;
do{
std::cout << "Podaj nazwe pliku(wraz z rozszerzeniem): "; //Insert filename.
std::cin >> filename;
std::cout << std::endl;
file.open(filename);
}while (!file.is_open());
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
if(file >> text){
A[i][j] = std::stod(text, 0);
}
else{
break;
}
}
}
file.close();
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
std::cout << A[i][j] << " ";
}
std::cout << std::endl;
}
}
推荐阅读
- java - 将 Collectors maxBy 与 groupingBy 一起使用时展开可选
- ios - 如何将字典从一个视图控制器类传递到另一个?SWIFT
- angular - Angular 单元测试模拟服务
- html - 如何将单独类型的文本定位到我制作的另一个文本的同一行中?
- excel - Excel-Pivot 扩展字段
- python - 使用 python 与 JSON 交互的更快方法
- python - 如何返回多个文件的第一行?
- validation - Cakephp 3.4 - 如何验证关联的关系数据?
- python - django huey 在过滤时总是返回空查询集
- c - C 语言中的双二阶滤波器示例实现