[英]C++ read txt data and char into 2D array
I would like to read text into arrayA[][] which includes data and characters. 我想将文本读取到arrayA [] []中,其中包括数据和字符。 It seems like
这好像是
And I need to calculate the data then. 然后我需要计算数据。 My code cannot do that.
我的代码无法做到这一点。 I try to output A[][] to see if there is anything wrong and it turns out that all the elements are 0.000.
我尝试输出A [] []以查看是否有任何错误,事实证明所有元素均为0.000。 Please help me to find out how to change it.
请帮助我找出如何更改它。 Thanks!
谢谢!
enter code here
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <fstream>
#include <limits>
int p = 518868;
int q = 11;
int s, t, i, j, k, m, d, r, u;
double A[518868][11];
int main(void)
{
FILE *fid;
using namespace std;
ifstream file("dump600.txt");
if (file.is_open())
{
for (i = 1; i <= p; i++)
{
for (j = 1; j <= q; j++)
{
file >> A[i][j];
}
}
}
fid = fopen("RstA600.txt", "wt");
for (i = 1; i <= 10000; i++)
{
for (j = 1; j <= 11; j++)
{
if (j == 11)
{
fprintf(fid, "%f\n", A[i][j]);
}
else
{
fprintf(fid, "%f\t", A[i][j]);
}
}
}
fclose(fid);
dump600.txt
id type x y z c_q[1] c_q[2] c_q[3] c_q[4] x y
1 1 0 0 30 -0.0075608 -0.710037 0.703789 0.021699 0 0
3 1 10 0 30 0.0138984 -0.409617 0.0338428 -0.911523 10 0
5 1 20 0 30 -0.31169 -0.685503 0.450455 0.479609 20 0
7 1 30 0 30 -0.194787 -0.373789 0.511419 -0.74886 30 0
The problem seems to be the first line containing text, which will let any file >> A[i][j]
fail. 问题似乎是包含文本的第一行,这将使任何
file >> A[i][j]
失败。 To overcome this, you could skip the first line using a std::getline
; 为了克服这个问题,您可以使用
std::getline
跳过第一行; also consider to somehow react on invalid input. 还考虑对无效输入做出反应。 Further, indexes in C++ start with
0
, not with 1
, such that for (j = 1; j <= q; j++)
and so on run out of bounds and yield undefined behaviour. 此外,C ++中的索引以
0
开头,而不是以1
开头,从而for (j = 1; j <= q; j++)
等,超出范围并产生未定义的行为。 See a sample of code that should work: 请参阅应该起作用的代码示例:
if (file.is_open())
{
std::string line;
if(std::getline(file, line)) {
for (i = 0; i < p; i++)
{
for (j = 0; j < q; j++)
{
if (!file >> A[i][j]) {
cout << "Invalid input.";
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.