[英]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. 使用像
coef1
, coef2
等单个实体不是很有用。 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: 注意事项:
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. N
系数。 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. 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. 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.