简体   繁体   English

C:整数无法正确打印

[英]C: integers not printing correctly

(Hi guys. I tried searching for the problem I'm having and can't seem to find the solution so far. I'm totally new to programming and am learning C currently, but I am a complete noob so I apologize in advance if I'm making a dumb mistake.) (大家好。我尝试搜索目前遇到的问题,到目前为止似乎找不到解决方案。我是编程新手,目前正在学习C,但是我是一个完全菜鸟,所以我提前道歉如果我犯了一个愚蠢的错误。)

Here's the problem: Im tryna scan 4 integers and print their values using a while loop. 问题出在这里:Im tryna扫描4个整数,并使用while循环打印它们的值。 The problem is, the numbers are being printed as crazy long numbers not as the ints that are input. 问题是,数字被打印为疯狂的长数字,而不是输入的整数。 I tried scanning and printing a single int and it printed fine but once I use multiple ints, it starts screwing aroud. 我尝试扫描和打印单个int,但打印效果很好,但是一旦使用多个int,它就会开始拧紧。

Here's my code: 这是我的代码:

#include <stdio.h>

int main()
{
    int i, n1,n2,n3,n4;
    printf("Enter 4 numbers.");
    for(i=0;i<4;i++)
    {
        printf("\n\nEnter number %d: ", i+1);
        scanf("%d,%d,%d,%d", &n1,&n2,&n3,&n4);
        printf("%d,%d,%d,%d", n1,n2,n3,n4);
    }

}

Two things: 两件事情:

  1. the input format given in scanf() should match exactly to the input value for a successful scan . scanf()给出的输入格式应与输入完全匹配,以成功进行扫描 [You need to have , s in your input] [你需要有,在你输入]
  2. Always check for the success of scanf() to ensure proper scanning of value. 始终检查scanf()是否成功,以确保正确扫描值。 scanf() returns the number of items successfully matched and scanned. scanf()返回成功匹配和扫描的项目数。

So, you should change your code to something like, 因此,您应该将代码更改为

 if ( scanf("%d,%d,%d,%d", &n1,&n2,&n3,&n4) == 4)
 {
       // use n1, n2, n3, n4
 }
 else
   //don't use them, return some error.

Note: Always initialize local variables. 注意:始终初始化局部变量。 Many a time it will save you from the undefined behaviour of read-before-write scenario. 很多时候,它将使您免于写前读取方案的不确定行为。

Also, [maybe?] the for loop is not required, as you're scanning all the four numbers at a time. 另外,[也许?]不需要for循环,因为您一次要扫描所有四个数字。

When you have scanf("%d,%d,%d,%d", &n1,&n2,&n3,&n4); 当您拥有scanf("%d,%d,%d,%d", &n1,&n2,&n3,&n4);

you must give your input as say 1,2,3,4 ( commas are needed) 您必须按1,2,3,4的要求输入(需要commas

And you said you want to read 4 numbers and you have a scanf that gets the 4 numbers. 您说要读取4个数字,并且有一个scanf可以获取4个数字。 So there is no need for a loop here. 因此,这里不需要循环。 If you want to loop get one number each time inside the loop. 如果要循环,则每次在循环内获取one number

You are looping 4 times, expecting to read 4 numbers in each loop... 您正在循环4次,希望在每个循环中读取4个数字...

Generally speaking, scanf() is a poor tool for parsing any kind of input that might not match the expected format -- and nothing is as fickle as user input. 一般而言, scanf()对于解析可能与预期格式不匹配的任何类型的输入来说是一个差劲的工具-而且没有什么比用户输入更善变了。 I usually advise reading in whole lines of input (via fgets() ), and then parsing them in-memory as appropriate (which, in this case, would probably mean using strtol() and checking how much of the input string was parsed via its second parameter). 我通常建议读取整个输入行(通过fgets() ),然后根据需要在内存中对其进行解析(在这种情况下,这可能意味着使用strtol()并检查通过解析了多少输入字符串)其第二个参数)。

This, for example, is much more robust: 例如, 更加健壮:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define LINELEN_MAX 100

int main()
{
    int i;
    char input[ LINELEN_MAX ];
    char * current;
    char * end;

    while ( 1 )
    {
        // whitespaces or commas do not matter,
        // and neither does the amount of numbers.
        puts( "Enter numbers, or 'q' to quit." );

        if ( fgets( input, LINELEN_MAX, stdin ) == NULL )
        {
            puts( "Error on read." );
            return EXIT_FAILURE;
        }
        if ( *input == 'q' )
        {
            puts( "Quitting." );
            return EXIT_SUCCESS;
        }
        if ( input[ strlen( input ) - 1 ] != '\n' )
        {
            puts( "Line exceeded maximum width." );
            return EXIT_FAILURE;
        }

        current = input;
        end = input;

        while ( *current )
        {
            if ( !isdigit( *current ) )
            {
                // skip non-digits
                ++current;
            }
            else
            {
                // parse 1..n digits and print
                printf( "%ld\n", strtol( current, &end, 10 ) );
                current = end;
            }
        }
    }
}

One reason may be that all your values are being printed onto the same line without any space between them. 原因之一可能是您的所有值都被打印在同一行上,而它们之间没有任何空格。

Basically you are printing 4 numbers continuously in one line which makes it look like one big number. 基本上,您正在一行中连续打印4个数字,这使其看起来像一个大数字。

I advise you to add a new line format specifier.(If you are a newbie, then you might not understand this, so here are some links that may be useful) 我建议您添加一个新的行格式说明符。(如果您是新手,那么您可能不理解这一点,因此这里有一些有用的链接)

http://www.codingunit.com/printf-format-specifiers-format-conversions-and-formatted-output http://www.codingunit.com/printf-format-specifiers-format-conversions-and-formatted-output

There is also the problem that you are reading 4 numbers 4 times , that is you are reading 16 variables in total. 还有一个问题,您正在读取4个数字4次,即总共要读取16个变量。 For this code , you actually don't need a for loop. 对于此代码,您实际上不需要for循环。

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

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