c - 在 C 中存储来自字符串的两个整数

标签 c string integer c-strings

我正在尝试编写一个程序,从一个字符串中打印两个数字。

例如,string = '20,66' 我试图将这个字符串分开,这样我就可以将 '20' 和 '66' 存储到两个单独的变量中。

这是我正在处理的代码:

#include <stdio.h>

char line[80];

int main(void)
{
    // Variables
    int start_number, end_number;
    int i, j;

    while(1)
    {
        printf("Enter a number: ");
        fgets( line, sizeof(line), stdin);

        // How to find Comma
        for( i=0; i < strlen(line); i++)
        {
            if(line[i]==',') break;
        }

        // How to find two numbers
        for(j = 0; j < i; j++)
        {
            printf("1: %c\n", line[j]);         
        }

        for(j = i + 1; j < strlen(line); j++)
        {
            printf("2: %c\n", line[j]);
        }

        if (strcmp(line, "quit\n") == 0)
        {
            printf("Now terminating program...");
            break;
        }       

    }   
}

到目前为止,我只能存储个位数变量,并且出于某种原因打印了额外的一行。

如有任何建议或建议,我们将不胜感激。

最佳答案

很简单:

const char *text = "20,30";
const char *rest = 0;
int first = strtol(text, &rest, 10); // input, pointer to remaining string, base (10 = decimal)
rest += 1; // skip the comma; this is error prone in case there are spaces!
int second = strtol(rest, NULL, 10); // not interested in remaining string, so pass NULL this time

关于c - 在 C 中存储来自字符串的两个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7668013/

相关文章:

OCaml 中的整数取幂

c - 与液晶屏连接图片

c - 为什么我不能在函数中对指向数组的指针使用 realloc?

c# - 根据自定义格式验证字符串

java - 如何在 Java 中安全地编码字符串以用作文件名?

c - 在 C 中将浮点值缩放为 (0-100) 的函数

int 和 long 可以是同一类型吗?

c - 如何将空格字符添加到字符串/字符数组?

string - 如何在 golang 中拆分长结构标签?

c - 是否有 LARGEST_INTEGER 宏或类似的东西? (C)