我有一个带有值的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';
}
}
}
答案 0 :(得分: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);
}
}