如何从c中将空格分隔的浮点数提取到另一个数组?

时间:2017-01-13 23:21:34

标签: c arrays space cs50

我有这个代码。用户应输入类似“10.0 10.0 4.0 7.0”的内容。并且,我希望我的程序将这些浮点数放入一个数组,以便通过浮点数[0] = 10.0,浮点数[1] = 10.0浮点数[2] = 4.0浮点数[3] = 7.0 即可。我稍后会把它们变成浮点类型。在这段代码中,我试图使用二维数组,但肯定是错误的。

你能让我走上正轨吗?

#include <cs50.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>

int main(void)
{   
    // prompt the user to enter two inputs 
    string input1 = get_string();

    // declare and initialize essential variables
    int len1 = strlen(input1);
    int j = 0;

    // declare an array where the next lines of code should put floats separately
    string floats[100][100];

    // put each floating point number into an array character by character
    for (int i = 0; i < len1; i++) {
        if (isspace(input1[i])) {
            j++;
        } else {
            floats[j][i] = input1[i];
        }
    }
}

3 个答案:

答案 0 :(得分:2)

strtod() is the best tool用于解析浮点数。

要使用空格分隔子字符串,OP的代码至少不附加所需的空字符。此外,从input1[]复制需要复制的不仅仅是一个字符。

// Avoid magic numbers, using define self-documents the code
#define FLOAT_STRING_SIZE 100
#define FLOAT_STRING_N 100

int main(void) {   
  string floats[FLOAT_STRING_N][FLOAT_STRING_SIZE];
  string input1 = get_string();
  char *p = input1;

  int count;
  for (count = 0; count < FLOAT_STRING_N; count++) {
    while (isspace((unsigned char) *p) p++;

    // no more
    if (*p == '\0') break; 

    int i;            
    for (i = 0; i<FLOAT_STRING_SIZE-1; i++) {
      if (isspace((unsigned char) *p) || *p == '\0') break;
      floats[count][i] = *p++;  // save character and advance to next one.
    }
    floats[count][i] = '\0';
  }

  int count;
  for (int c = 0; c < count; c++) {
    puts(floats[c]);
  }

  return 0;
}

答案 1 :(得分:1)

您可以使用strtod()一次解析字符串一个浮点数:

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

int main(void) {   
    // prompt the user to enter two inputs 
    char *input1 = get_string();

    // declare the destination array for the floating point numbers
    double numbers[100];
    int n;

    char *p = input1;
    char *q;

    for (n = 0; n < 100; n++) {
        numbers[n] = strtod(p, &q);
        if (p == q) {
            // no more numbers to parse
            break;
        }
        p = q;
    }

    // print the array contents
    for (int i = 0; i < n; i++) {
        printf("%f\n", numbers[i]);
    }

    return 0;
}

答案 2 :(得分:0)

您可以使用stringstream(尽管这是一种c ++方式),就像这样

std::stringstream ss;
ss.str (input1);
int i = 0;
string t;
while ( ss >> t) 
{
     floats[i++] = std::stof(t); //fill your array one by one
}

对于纯C方式,您可以使用sscanf。