从字符串中获取整数

huangapple go评论60阅读模式
英文:

Getting an integer from a string

问题

以下是您提供的代码的翻译部分:

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

int main() {
    char a[20];
    int p = 0;
    while (scanf("%s", a)) {
        sscanf(a, "%d", &p);
        if (p != 0) {
            printf("yes");
        } else {
            printf("no");
        }
    }
    return 0;
}

另外,您提到的输出:

printf("%d", p);

对于输入:

name 1

它打印出:

0no1yes

如您所说,它首先将整数设置为0,然后在进入if语句之后才变为1

英文:

I have some code that reads a string of the form name 1 in a while loop, and then I have to extract the integer value to print yes or no. But when I tried to do it with sscanf, it gives the destination integer the value only after the loop finishes.

#include &lt;stdio.h&gt;
#include &lt;string.h&gt;
#include &lt;stdlib.h&gt;

int main() {
    char a[20];
    int p = 0;
    while (scanf(&quot;%s&quot;, a)) {
        sscanf(a, &quot;%d&quot;, &amp;p);
        if (p != 0) {
            printf(&quot;yes&quot;);
        } else {
            printf(&quot;no&quot;);
        }
    }
    return 0;
}

even though the string I introduce has the integer greater than 1, the program always prints no.

I tried to evaluate the output with printfs and I saw that when I execute it gives this output:

printf(&quot;%d&quot;, p);

For the input:

name 1

it prints:

0no1yes

As I said, it first gets the integer as 0 and after entering the if it becomes 1.

答案1

得分: 2

  1. 总是格式化你的代码。不是为了我们 - 而是为了你自己
  2. 总是检查 scanf 的结果
  3. 不要使用 scanf 读取行 - 总是使用 fgets
int main(void)
{
    char a[20];
    int p = 0;
    while (fgets(a, sizeof(a), stdin))
    {
        if (sscanf(a, "%d", &p) != 1)
        {
            printf("\nNo no no!!!!\n");
            continue;
        }
        if (p != 0)
        {
            printf("yes\n");
        }
        else {
            printf("no\n");
        }
    }
    return 0;
}

链接至代码

英文:
  1. ALways format your code. Not for us - for yourself
  2. Alays check the result of scanf
  3. Do not use scanf to read lines - always use fgets
int main(void)
{
    char a[20];
    int p=0;
    while(fgets(a, sizeof(a), stdin))
    {
        if(sscanf(a,&quot;%d&quot;,&amp;p) != 1) 
        {
            printf(&quot;\nNo no no!!!!\n&quot;);
            continue;
        }
        if(p!=0)
        {
            printf(&quot;yes\n&quot;);
        }
        else{
        printf(&quot;no\n&quot;);
        }
    }
    return 0;
}

https://godbolt.org/z/dcqc47vh1

答案2

得分: 2

在这个scanf调用中:

while(scanf("%s",a)) {

转换说明符s 只允许读取由空格分隔的文本。如果你输入:

name 1

那么第一次 scanf 调用将只读取文本 "name",而在循环的下一次迭代中,scanf 调用将读取文本 "1",这确实可以转换为整数。

你需要在 scanf 调用中使用另一个转换说明符。

而且,在 while 循环的条件中:

while(scanf("%s",a)) {

实际上你有一个无限循环。

此外,你的程序包含了多余的包含指令。

程序可以如下所示:

#include <stdio.h>

int main( void ) 
{
    char a[20];

    while ( scanf(" %19[^\n]", a ) == 1 ) 
    {
        int p = 0;

        sscanf( a, "%*s%d", &p );

        if ( p ) 
        {
            puts( "yes" );
        }
        else 
        {
            puts( "no" );
        }
    }

    return 0;
}
英文:

In this call of scanf

while(scanf(&quot;%s&quot;,a)) {

the conversion specifier s allows to read only a text that is separated by spaces. That is if you will enter

name 1

then the first call of scanf will read only the text &quot;name&quot; and in the next iteration of the loop the call of scanf will read the text &quot;1&quot; that indeed can be converted to an integer.

You need to use another conversion specifier in the call of scanf.

And the condition in the while loop

while(scanf(&quot;%s&quot;,a)) {

In fact you have an infinite loop.

Also your program contains redundant include directive.

The program can look the following way.

#include &lt;stdio.h&gt;

int main( void ) 
{
    char a[20];

    while ( scanf(&quot; %19[^\n]&quot;,a ) == 1 ) 
    {
        int p = 0;

        sscanf( a,&quot;%*s%d&quot;, &amp;p );

        if ( p ) 
        {
            puts( &quot;yes&quot; );
        }
        else 
        {
            puts( &quot;no&quot; );
        }
    }

    return 0;
}

答案3

得分: 0

When you use scanf() to read input values from the standard input stream, it stores the input values in a buffer until it reads all the expected input values. If you do not consume all the input values in the buffer, they can remain in the buffer and can cause issues in your program. Therefore better to use fgets() method to read data from the input stream.

英文:

When you use scanf() to read input values from the standard input stream, it stores the input values in a buffer until it reads all the expected input values. If you do not consume all the input values in the buffer, they can remain in the buffer and can cause issues in your program. Therefore better to use fgets() method to read data from input stream.

#include &lt;stdio.h&gt;

int main(){
    char inpt[20];
    char str[20];
    int val=0;
    while(1){
        fgets(inpt, 20, stdin);
        sscanf(inpt, &quot;%s %d&quot;, str, &amp;val);
        if(val!=0){
            printf(&quot;yes\n&quot;);
        }
        else{
            printf(&quot;no\n&quot;);
        }
    }
    return 0;
}

答案4

得分: 0

You have almost the correct approach: you should read a line of input with fgets() and then parse it with sscanf() to extract the integer.

As coded, reading with scanf("%s", a) is both incorrect and risky:

  • incorrect because only a single word is read, name, then 1 in the next loop.
  • risky because any word longer than 19 characters will cause a buffer overflow.

Here is a simple alternative:

#include <stdio.h>

int main(void) {
    char a[100];

    while (fgets(a, sizeof a, stdin)) {
        int p;
        if (sscanf(a, "%*s%d", &p) == 1 && p != 0)
            puts("yes");
        else
            puts("no");
    }
    return 0;
}

Note however that the above code will accept potentially invalid lines such as Hello 1 world! and 1 2 3

英文:

You have almost the correct approach: you should read a line of input with fgets() and then parse it with sscanf() to extract the integer.

As coded, reading with scanf(&quot;%s&quot;, a) is both incorrect and risky:

  • incorrect because only a single word is read, name, then 1 in the next loop.
  • risky because any word longer than 19 characters will cause a buffer overflow.

Here is a simple alternative:

#include &lt;stdio.h&gt;

int main(void) {
    char a[100];

    while (fgets(a, sizeof a, stdin)) {
        int p;
        if (sscanf(a, &quot;%*s%d&quot;, &amp;p) == 1 &amp;&amp; p != 0)
            puts(&quot;yes&quot;);
        else
            puts(&quot;no&quot;);
    }
    return 0;
}

Note however that the above code will accept potentially invalid lines such as Hello 1 world! and 1 2 3

答案5

得分: -1

Your input is "name 1" so the first read of sscanf is not "successful" because it first reads "name" and it's not an integer, either, as suggested try to check how many successful reads you have or (if you trust the input) try with

sscanf("%s %d", a, &p);

and now the sscanf will know to skip the string and read the integer you want.

英文:

Your input is "name 1" so the first read of sscanf is not "successful", because it first reads "name" and it's not an integer, either, as suggested try to check how many successful reads you have or (if you trust the input) try with

sscanf(&quot;%s %d&quot;, a, &amp;p);

and now the sscanf will know to skip the string and read the integer you want.

huangapple
  • 本文由 发表于 2023年4月7日 04:37:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75953571.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定