简体   繁体   English

atoi() 由于特殊字符而不转换整个字符串

[英]atoi() not converting whole string because of special character

I have data in my.txt file containing different time ins and time outs of employees.我在 my.txt 文件中有数据,其中包含员工的不同时间进出。 For example, 10:20 but I initially designed the structure to have their data types to be of char arrays or string.例如,10:20,但我最初将结构设计为使其数据类型为 char 10:20或字符串。 Since I'll be using the time values in another function, I have to use the atoi() function to convert them into integer values.由于我将在另一个 function 中使用时间值,因此我必须使用 atoi() function 将它们转换为 integer 值。 Problem is, there is a colon : in each of the time values.问题是,每个时间值都有一个冒号: Would it be possible to convert the string 10:20 to an integer using atoi() so that I can it in my future functions?是否可以使用 atoi() 将字符串10:20转换为 integer 以便我可以在未来的函数中使用它? Does the use of atoi() allow some splitting or some sort so that I can convert my time value from string to int? atoi() 的使用是否允许进行一些拆分或某种排序,以便我可以将时间值从字符串转换为 int?

I tried我试过了

char time[10] = "10:20";

int val;

printf("string val = %s, int value = %d", time, atoi(time));

But my output is only string val = 10:20, int value = 10 so only the string before the : is read and converted to string.但是我的 output 只有string val = 10:20, int value = 10所以只有:之前的字符串被读取并转换为字符串。 I would want that after converting, I would stil have 10:20 as the result but in integer because I am going to use relational operators with it.我希望在转换后,我仍然会得到 10:20,但在 integer 中,因为我将使用关系运算符。

It's not clear what you actually want, but maybe something like:目前尚不清楚您真正想要什么,但可能类似于:

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

int
main(int argc, char **argv)
{
        char *time = argc > 1 ? argv[1] : "10:20";
        int d;
        char *e;

        d = strtol(time, &e, 10);
        if( *e == ':' ){
                d *= 100;
                d += strtol(e + 1, &e, 10);
        }
        if( *e != '\0' ){
                fprintf(stderr, "invalid input\n");
                return 1;
        }

        printf("string val = %s, int value = %d\n", time, d);
        return 0;
}

This will produce d = 1020 for the string "10:20".这将为字符串“10:20”生成d = 1020 It's not at all clear to me what integer you want to produce, but that seems to be what you're looking for.我完全不清楚你想要生产什么 integer ,但这似乎就是你想要的。

You can also use sscanf :您还可以使用sscanf

#include <stdio.h>

int main() {
  char const* time = "10:20";

  int h, m;
  if (sscanf(time, "%d:%d", &h, &m) != 2)
    return 1;

  printf("string val = %s, int value = %d\n", time, h * 100 + m);
}

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

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