简体   繁体   English

Printf()函数表现奇怪

[英]Printf() function acting strange

Apologies if this question is stupid, I'm new to coding, especially in C++. 抱歉,如果这个问题很愚蠢,我是编码新手,尤其是在C ++中。 I'm trying to read in data points from a space-separated text and then use the printf function to get it output them to the console. 我试图读取以空格分隔的文本中的数据点,然后使用printf函数将其输出到控制台。 When I try this; 当我尝试这个

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main() {
    double x[1000];
    int i = 0;
    int j;
    double y[1000];
    double sigmay[1000];

    ifstream dataFile("xys_test.txt");

    if (dataFile.is_open()) {
        while (!dataFile.eof())
        dataFile >> x[i] >> y[i] >> sigmay[i];
        printf("x = %5.2f, y = %5.2f, sigmay = %5.2f\n", x[i], y[i], sigmay[i]);
    i++;
}
}

All the console output gives me is the last data point, when I was hoping that all the points would be output into the console. 当我希望所有这些点都将输出到控制台中时,控制台输出给我的是最后一个数据点。 How can I resolve this? 我该如何解决?

You are missing a pair of { ... } for the contents of your while block. 您缺少while块内容的一对{ ... } Currently, only the dataFile >> x[i] >> y[i] >> sigmay[i]; 当前,只有dataFile >> x[i] >> y[i] >> sigmay[i]; line is inside the while block. 行在while块内。

if (dataFile.is_open()) {
    while (!dataFile.eof()) {
        dataFile >> x[i] >> y[i] >> sigmay[i];
        printf("x = %5.2f, y = %5.2f, sigmay = %5.2f\n", x[i], y[i], sigmay[i]);
        i++;
    }
}

you lost your curly bracket, 你失去了花括号,

while (!dataFile.eof()) {
  dataFile >> x[i] >> y[i] >> sigmay[i];
  printf("x = %5.2f, y = %5.2f, sigmay = %5.2f\n", x[i], y[i], sigmay[i]);
  i++;
}

The code should be: 代码应为:

while ( i < 1000 && (dataFile >> x[i] >> y[i] >> sigmay[i]) )
{
    printf("x = %5.2f, y = %5.2f, sigmay = %5.2f\n", x[i], y[i], sigmay[i]);
    ++i;
}

You should test whether or not the read operation succeeded, in order to decide whether to proceed with printing and committing the data. 您应该测试读取操作是否成功,以便决定是否继续打印和提交数据。 Testing eof is irrelevant and a mistake. 测试eof无关紧要并且是错误的。

Also #include <cstdio> should be used for printf . 同样, #include <cstdio>也应用于printf Possibly your compiler/library setup involves cstdio being included by iostream but in general that is not the case. 可能是您的编译器/库设置涉及iostream包含cstdio,但通常情况并非如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM