简体   繁体   English

如何创建一个程序,该程序将读取c中用逗号分隔的无限用户输入字符串?

[英]How do I create a program that will read infinite user input strings separated by commas in c?

I have this code that needs to compute for the rational roots of a polynomial 我有这段代码需要计算多项式的有理根

int n,co;
char coef1[10],coef2[10],coef3[10],coef4[10];

printf("Enter the highest degree of the input polynomial:");
scanf("%d",&n);

co=n+1;

printf("Enter %d integer coefficients starting from the 0th degree\n", co);

printf("Separate each input by a comma:");

This part was only used as a test if user input would be read correctly when the degree entered is 2 此部分仅用作测试,当输入的程度为2时,是否可以正确读取用户输入

scanf("%10[^,],%10[^,],%s",coef1,coef2,coef3,coef4);

printf("%s %s %s",coef1,coef2,coef3);

My problem is how to print %10[^,] the same number of times as n that the user inputs (which should be possible for infinite input)and to add %s to the end. 我的问题是如何打印%10 [^,]的次数与用户输入的n相同(对于无限输入来说应该是可能的),并在末尾添加%s。 Also,even if I do that, I would need a way to declare coef1,coef2 etc. the same number of times as co. 另外,即使我这样做,我也需要一种方法来声明coef1,coef2等与co相同的次数。

It's not quite clear what you want. 不清楚您想要什么。 I assume that you want to read in a set of coefficients and keep track of how many coefficients were entered. 我假设您想读取一组系数并跟踪输入了多少个系数。

scanf isn't suited to this approach, because you already have to specify how many parameters you want to read in the format file. scanf不适合这种方法,因为您已经必须指定要在格式文件中读取多少个参数。 scanf also doesn't recognise new lines, so that a line-based format cannot be read without a baroque format syntax. scanf也不识别新行,因此如果没有巴洛克式格式语法,就无法读取基于行的格式。 fgets reads whole lines. fgets读取整行。 strtok separates strings at certain separators. strtok在某些分隔符处分隔字符串。 You could use a combination of these. 您可以结合使用这些。

Next, you should determine how you want to store your coefficients. 接下来,您应该确定如何存储系数。 Using individual entities like coef1 , coef2 and so on is not very useful. 使用像coef1coef2等单个实体不是很有用。 Use an array. 使用数组。

Putting ths into practice (albeit for floting-point coefficnents), you get: 将其付诸实践(尽管有浮点系数),您将获得:

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

#define N 10

int coeff_read(char *line, double  coeff[], int max)
{
    int n = 0;
    char *token = strtok(line, ",");

    while (token) {
        char *tail;
        double x = strtod(token, &tail);

        if (tail == token) return -1;

        if (n < max) coeff[n] = x;
        n++;

        token = strtok(NULL, ",");
    }

    return n;
}

void coeff_print(const double *coeff, int n)
{
    for (int i = 0; i < n; i++) {
        if (i) printf(", ");
        printf("%g", coeff[i]);
    }
    puts("");
}

int main()
{
    char line[200];
    double coeff[N];
    int ncoeff;

    while (fgets(line, sizeof(line), stdin)) {
        ncoeff = coeff_read(line, coeff, N);

        if (ncoeff < 0) {
            puts("Invalid input.");
            continue;
        }

        if (ncoeff > 0) {
            if (ncoeff > N) ncoeff = N;
            coeff_print(coeff, ncoeff);
        }
    }

    return 0;
}

Things to note: 注意事项:

  • The array has a fixed number of entries, N . 该数组具有固定数量的条目N Only ncoeff of these are valid. 其中只有ncoeff有效。 This is a usual approach in C, but it means that you input will have at most N coefficients. 这是C语言中的常用方法,但是这意味着您输入的内容最多具有N系数。
  • If you really want "infinite" input, you must cater for big arrays. 如果您确实想要“无限”输入,则必须迎合大型数组。 Dynamic allocation can provide arrays of variable size. 动态分配可以提供可变大小的数组。 That's an advanced topic. 这是一个高级话题。 (The function coeff_read returns the actual number of coefficients, which may be more than the array size. That's not useful in this example, but you could use this information to scan the string with max == 0 , allocate as appropriate and then scan again with the allocated data.) (函数coeff_read返回实际的系数数目,该数目可能大于数组的大小。在此示例中这没有用,但是您可以使用此信息来扫描max == 0的字符串,进行适当分配,然后再次进行扫描分配的数据。)
  • strtok considers runs of consecutive commas like so ,,, as one single separator. strtok认为像这样连续的逗号的运行,,,作为单个分离器。 If, for example, you want empty entries to mean zero, you'll have to use another method. 例如,如果您希望空条目表示零,则必须使用另一种方法。
  • There's another limitation here: The maximum line length. 这里还有另一个限制:最大行长。 If you are going for infinite or at least very long input, you cannot be sure that the line length is sufficient. 如果要输入无限或至少非常长的输入,则不能确保行长足够。 You will need another solution. 您将需要其他解决方案。
  • The library function strtod provides more information in its return value, in the tail pointer and in the library's error code, errno . 库函数strtod在其返回值,尾指针和库的错误代码errno提供了更多信息。 You could make use of it in order to find out whether the number is out of range or has extra cahacter after it. 您可以利用它来确定数字是否超出范围或后面是否有多余的字符。 For the sake of simlicity (and laziness), I haven't. 为了简单起见(和懒惰),我没有。
  • You want integers instead of floating-point numbers. 您需要整数而不是浮点数。 The library function strtol is the integer equivalent to strtod . 库函数strtol是与strtod等效的整数。

Do not recommend infinite input as that is a security hole. 不建议无限输入,因为这是一个安全漏洞。 Instead allow many. 而是允许许多。

To use scanf("%lf", &data) within a line, need to first look for '\\n' with other code. 要在一行中使用scanf("%lf", &data) ,首先需要在其他代码中查找'\\n'

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

int GetLineOfDoubles(FILE *stream, double *dest, size_t length) {
  int i = 0;
  int ch;

  while (1) {
    while (isspace(ch = fgetc(stream)) && ch != '\n')
      ;
    if (ch == '\n' || ch == EOF) break;

    if (i > 0) {
      if (ch != ',') return 0; // Missing comma

      while (isspace(ch = fgetc(stream)) && ch != '\n')
        ;
      if (ch == '\n' || ch == EOF) return 0;  // Missing data
    }

    ungetc(ch, stdin);

    double data;
    if (scanf("%lf", &data) != 1) return 0; // Bad data
    if (i == length) return 0; // Too much data
    dest[i++] = data;
  }

  if (i > 0) return i;
  return ch == EOF ? EOF : 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C如何读取逗号分隔的输入 - C how to read input separated by commas 如何在C中用逗号分隔的字符串中扫描数字 - How to scan for numbers in strings separated by commas in c 如何使用用户的输入C程序创建一个外部循环以读取两个单独的迷宫 - How do you create an outer loop to read two separate mazes using the user's input C program 如何在 C 中将字符串与不确定的用户输入分开? - How do I separate strings from uncertain user input in C? 如何在输入长度未知的情况下读取以逗号分隔的数字? - How to read numbers separated by commas where the input is of unknown length? 如何仅使用 C fscanf() 读取以逗号分隔的多个变量 - how to read multiple variables separated by commas using only C fscanf() 尝试创建将用户输入字符串与C中的一组预定义输入字符串进行比较的程序 - Trying to create program that compares user-input strings to a set of predefined input strings in C C:如何将用户输入限制为2个以空格分隔的参数? - C: How do you limit user input to 2 arguments separated by a space? 如何在c中读取以“:”分隔的两个字符串 - How to read two strings separated by “:” in c 在C语言中,我如何只接受某些字符串并继续要求用户输入,直到输入了有效的输入? - In C, how do I only accept certain strings and continue to ask the user for input until valid input is entered?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM