复制值成整数

问题描述:

我与值txt文件:复制值成整数

1 -200 3 4

如何获得的长度输入(以便我可以告诉代码在哪里停止)并在空白之前复制值?即我想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); 
    } 
} 
+0

辉煌!虽然有些令人困惑,但希望通过测试和打印声明,我可以找出背后的步骤。 谢谢! – 2015-03-31 03:23:01

+0

该代码只读取一行;原始代码读取多行。我认为'while(fgets(buffer,sizeof(buffer),stdin)!= NULL)'循环是适当的。 – 2015-03-31 04:04:27