gpt4 book ai didi

将值从 char[] 复制到整数

转载 作者:行者123 更新时间:2023-11-30 17:17:43 24 4
gpt4 key购买 nike

我有一个 txt 文件,其值是:

1 -200 3 4

2 3 5 7

如何获取输入的长度(以便我可以告诉代码在哪里停止)并复制空格之前的值?即我想要 a = 1, b = -200, c = 3, d = 4 (我尝试过的方法似乎仅以以下形式增加值:-2 + 0 + 0 = -2)

我正在处理的代码:

 char buffer[100];
char c;
int x = 0;
while (fgets(buffer, sizeof(buffer), stdin) != NULL){ // while stdin isn't empty
for (int i = 0; i < 10; i++){ // loop through integer i (need to change
//i < 10 to be size of the line)
if (strchr(buffer, c) != NULL){
// if there is a white space
// add the value of buffer to x
x += buffer[i] - '0';
}
}
}

最佳答案

试试这个,它没有 4 个数字相加的限制:

char buffer[100], 
char bufferB[100]; //holds the individual numbers
int x = 0, i = 0, j = 0;
//you dont need a while in fgets, because it will never be NULL (the '\n' will always be read)
if (fgets(buffer, sizeof(buffer), stdin) != NULL){
while(buffer[i] != '\n' && buffer[i] != '\0'){
//If we have not occured the white space store the character
if( buffer[i] != ' ' ){
bufferB[j] = buffer[i];

j++;
}
else{ //we have found the white space so now make the string to an int and add to x
bufferB[j] = '\0'; //make it a string

x += atoi(bufferB);

j = 0;
}

i++;
}

//The last number
if( j != 0 ){
bufferB[j] = '\0';

x += atoi(bufferB);
}
}

关于将值从 char[] 复制到整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29359465/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com