c - 如何将空格分隔的 float 从字符串中提取到 c 中的另一个数组中?

标签 c arrays space cs50

我有这个代码。用户应输入类似“10.0 10.0 4.0 7.0”的内容。而且,我希望我的程序将这些 float 放入一个数组中,以便可以通过 floats[0] = 10.0, floats[1] = 10.0 floats[2] = 4.0 floats[3] = 访问每个 float 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];
        }
    }
}

最佳答案

strtod() is the best tool用于解析 float 。

要使用空格分隔子字符串,至少 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;
}

关于c - 如何将空格分隔的 float 从字符串中提取到 c 中的另一个数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41644980/

相关文章:

css - 页脚上方的空白使用 CSS 位置 :fixed

c# - 如何使用 OpenXML 删除项目符号和段落之间的空白内容

jquery - DIV 之间的额外空间

C:读取二进制文件输出零

c - 如何显示 float

java - 不同算法的两个计数器数组的结果相同

c++ - 将数组内容传递给特定函数时数组内容会发生变化

javascript - 使用 php mysqli 插入 json 数组时出错

c - 为什么我不能在 Linux 中使用函数 grantpt?

c - 在c中读取bmp图像