当用户完成在c中的输入时停止for循环 [英] Stop a for loop when user is finished entering input in c
问题描述
我是新来的C语言(和一般编程),我试图写一个其中用户输入数据点的程序。数据点然后保存在一个数组中,然后可以被操纵。
在哪里我卡住了:我希望用户能够输入(几乎)任意数量的点,然后使用关键字排序来表示结束数据输入。在这种情况下,用户将键入完成。
这是我到目前为止:
#include< stdio.h中>
#include< string.h>
int main(void){
printf(\\\
欢迎!\\\
\\\
请输入每个数据点,完成后输入'done'。 \
\\\
);
双数据[1048];
int i,count; (i = 1;; i ++){
$ b printf(Data [%i]:,i);
scanf(%lf,& data [i]);
if(data [i] =='done'){
break;
} else {
count ++;
$ b code $ pre
我试过'return 1;'和'break;'。每一次,程序运行良好,直到输入关键字,在这一点上,我得到:
$ $ $ $ $ $ $ $ $数据[8]:数据[9]:...数据[1120]:数据[1分段错误11
唯一的时间它的工作原理是当用户输入一个特定的数字(比如-1或者0)的时候我有了它。但是这对用户来说并不合适,因为他们可能不得不将这些数字作为数据点输入。
很抱歉,很长的文章,但我非常感谢帮助! / p>
您已经收到了很多很好的答案,还有几种方法可以输入双打
并停在完成
。既然你在学习C语言,那么总是 总是 (如果不清楚的话),检查 scanf
来验证实际发生的转化次数。 [1] 结束输入done
(或任何非双输入导致 scanf
返回小于<$ c $如注释中所述,数组是基于 零的 。 在C中输入时,你需要使用 count
作为数组索引,而不是 i
(在这种情况下,如果您退出每次失败的读取 - 没有关系,但是您可以再次轻松地提示输入额外的内容,并且仅在一个输入上增加 count
从 scanf
成功返回)回到你的问题,如果你设置你的读循环继续循环,直到有一个 scanf
失败,你可以使用临时变量最初捕获输入值,只将值分配给您的数组,并成功增加您的索引。例如($ MAXD = 1048
)
for(;;) {/ *循环直到scanf输入失败('完成')* /
消除数组限制(
double tmp; / *块范围声明罚款* /
printf(data [%4d]:,count);
$ b $ if(count< MAXD& amp; scanf(%lf,& tmp)== 1)
data [count ++] = tmp;
else
break;
$(你甚至可以移动循环上面的提示副本,并移动如果(...){...}MAXD $ c> $ c>)已经到达了 - 这只是一个练习)
在上面的例子中,在存储一个值之前,你有两个条件需要执行。 (1)将用户可以存储的值限制为
MAXD
,(2)如果有效转换为double
发生在scanf
中。如果其中一个条件失败(如果您输入done
作为双精度值,则它将会退出)
将这些部分放在一起,并在注释中放入一些额外的提示,您可以使用类似以下的方法进行测试:
#include< stdio.h>
enum {MAXD = 1048}; / *声明常量而不是使用幻数* /
int main(void){
double data [MAXD] = {0}; / * ISO C声明在代码之前* /
int i,count = 0; / *初始化变量保存调试时间* /
printf(\\\
欢迎!\\\
\\\
请输入每个数据点。
完成时输入'done'。 \\\
\\\
); (;;){/ *循环直到scanf输入失败(带有'done')* /
double tmp;
/ *块范围声明罚款* /
printf(data [%4d]:,count);
$ b $ if(count< MAXD& amp; scanf(%lf,& tmp)== 1)
data [count ++] = tmp;
else
break;
printf(\ n%d values entered:\\\
\\\
,count); (i = 0; iprintf(data [%4d]:%.2lf\\\
,i,data [i])的
;
返回0; / * main()是类型'int'并返回值* /
}
示例使用/输出
$ ./bin/scanfdoubles
欢迎!
请输入每个数据点。完成后输入完成。
data [0]:1.1
data [1]:1.2
data [2]:1.3
data [3]:1.4
data [ 4]:1.5
data [5]:1.6
data [6]:完成
输入的6个值:
data [0]:1.10
data [1]:1.20
data [2]:1.30
data [3]:1.40
data [4]:1.50
data [5]:1.60
仔细查看,如果您有任何问题,请告诉我们。
脚注: 可以用
scanf
在C中进行用户输入,最好使用 / em>函数(如fgets
),然后解析完整的行(例如sscanf
)。 (1)验证读取(例如返回fgets
),然后(2)分别验证用户输入的值。这个 解耦 你的阅读,你的解析有很多好处。First of all, thank you for the assist!
I'm new to the C language (and programming in general) and I'm trying to write a program wherein the user inputs data points. The data points are then saved in an array where they can then be manipulated.
Where I am stuck: I want the user to be able to input (almost) any number of points, then use a 'keyword' of sorts to signal the end of data entry. In this case, the user would type 'done'.
Here's what I have so far:
#include <stdio.h> #include <string.h> int main(void) { printf("\n Welcome! \n\n Please enter each data point. Enter 'done' when finished.\n\n"); double data[1048]; int i, count; for (i = 1; ;i++) { printf("Data[%i]: ", i); scanf("%lf", &data[i]); if (data[i] == 'done') { break; } else { count++; } } }
I've tried 'return 1;' and 'break;'. Each time, the program works well until the 'keyword' is entered, at which point I get:
Data[8]: Data[9]: ... Data[1120]: Data[1Segmentation fault 11
The only time it works is if I have it break when the user inputs a particular number (like -1 or 0). But that doesn't quite work for the user since they might have to enter those numbers as data points.
Sorry for the long post, but I appreciate the help!
解决方案You have received a number of good answers to your question, and there are several more ways to take input of
doubles
and stop on"done"
. Since you are learning C, always, ALWAYS (in case it wasn't clear), check the return ofscanf
to validate the number of conversions you expected actually took place.[1] (this also provides your way to end input on"done"
(or any non-double entered causingscanf
to return less than1
)As noted in the comment, arrays are zero based in C. When you are taking input, you will want to use
count
as your array-index, rather thani
(in this case if you exit the read on each failure -- it doesn't matter, but you could just as easily prompt again for additional input and incrementcount
only on a successful return fromscanf
) Back to your question. If you set up your read loop to continually loop until there is ascanf
failure, you can make use of a temporary variable to initially capture the input value, and only assign the value to your array and increment your index on success. e.g. (with a constantMAXD = 1048
)for (;;) { /* loop until scanf input fails (with 'done') */ double tmp; /* block scope declarations are fine */ printf (" data[%4d]: ", count); if (count < MAXD && scanf(" %lf", &tmp) == 1) data[count++] = tmp; else break; }
(you can even move a copy of the prompt above the loop, and move the one above after the
if (....) {...}
to eliminate the prompt when the array limit (MAXD
) is reached -- that's left as an exercise)In the example above you have 2 conditions you enforce before storing a value. (1) you limit the number of values your user can store to
MAXD
, and (2) you only store a value if a valid conversion todouble
takes place inscanf
. You leave the loop if either of the conditions fails (which if you enter"done"
as a double-value, it will).Putting the pieces together and dropping a few additional tips in the comments, you could test with something like the following:
#include <stdio.h> enum { MAXD = 1048 }; /* declare constants instead of using magic numbers */ int main (void) { double data[MAXD] = {0}; /* in ISO C declarations come before code */ int i, count = 0; /* initializing variable saves debug time */ printf ("\n Welcome! \n\n Please enter each data point. " "Enter 'done' when finished.\n\n"); for (;;) { /* loop until scanf input fails (with 'done') */ double tmp; /* block scope declarations are fine */ printf (" data[%4d]: ", count); if (count < MAXD && scanf(" %lf", &tmp) == 1) data[count++] = tmp; else break; } printf ("\n %d values entered:\n\n", count); for (i = 0; i < count; i++) printf (" data[%4d] : %.2lf\n", i, data[i]); return 0; /* main() is type 'int' and returns a value */ }
Example Use/Output
$ ./bin/scanfdoubles Welcome! Please enter each data point. Enter 'done' when finished. data[ 0]: 1.1 data[ 1]: 1.2 data[ 2]: 1.3 data[ 3]: 1.4 data[ 4]: 1.5 data[ 5]: 1.6 data[ 6]: done 6 values entered: data[ 0] : 1.10 data[ 1] : 1.20 data[ 2] : 1.30 data[ 3] : 1.40 data[ 4] : 1.50 data[ 5] : 1.60
Look things over and let me know if you have any questions.
footnotes:
1. while you can use
scanf
to take user-input in C, you are better off using a line-oriented function (likefgets
) and then parsing the complete line (with, e.g.sscanf
). The allows you to both (1) validate the read (e.g. the return offgets
) and then (2) separately validate the value entered by the user. This decoupling of your read, and your parsing has many advantages.这篇关于当用户完成在c中的输入时停止for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!