how to read a single line integer until '\n' is found
2013-01-24 10:57
351 查看
Q: Write a C program that reads in several lists of numbers, one list per line, computes the
total for each list and displays the total on the screen. The user first enters the number of
lines. For each list of numbers, the first number indicates how many elements are in the
list.
A sample input and output session is given below:
Enter the number of lines:2
4 1 3 5 7
Output total: 16
5 2 4 6 8 1
Output total: 21
I'm a bit sad that i cannot even finish this simple program after learning C for a long time...
Hard word is still needed...
total for each list and displays the total on the screen. The user first enters the number of
lines. For each list of numbers, the first number indicates how many elements are in the
list.
A sample input and output session is given below:
Enter the number of lines:2
4 1 3 5 7
Output total: 16
5 2 4 6 8 1
Output total: 21
#include <stdio.h> #include <string.h> void clear(void) { while (getchar() != '\n'); } int main() { int n, i; printf("Enter the number of lines: "); scanf("%d", &n); clear(); //clear the input buffer such as ' ' and '\n' for (i=0; i<n; i++) { char buff[100]; printf("Please input numbers in a single line:\n"); fgets(buff, sizeof(buff), stdin); printf("The length of input is: %d\n", strlen(buff)); char *p; p = &buff[0]; int a, sum = 0; while (sscanf(p, "%d", &a) != 0) { sum += a; while (*p!= ' ' && *p!= '\n') //delete digits p++; while (*p == ' ' || *p == '\n') //delete space and newline p++; if (strlen(p) < 1) break; } printf("Output total: %d\n", sum); } }
I'm a bit sad that i cannot even finish this simple program after learning C for a long time...
Hard word is still needed...
相关文章推荐
- How to read file line by line?
- How to read a file line by line?
- [quote] How to read Perl command-line arguments.
- How to Convert a Single-Instance ASM to Cluster ASM [ID 452758.1]
- [quote] How to determine what target is given in Makefile from the make command-line?
- How to Convert a Single-Instance ASM to Cluster ASM [ID 452758.1]
- How To Read C Declarations(过目不忘的C语言类型声明)
- How to read Tcpdump Output | Tcpdump Advanced Use
- Compute how many bits to require convert one integer to another
- How To Read a Paper.md
- How do I upgrade a single MongoDB node to sharding mode?
- how to automate label printing with command line parameters
- How to Parse or Read XML File in Java >> XML Tutorial Example
- How To Use gflags (formerly Google Commandline Flags)
- How to read binary data from HDFS with Thrift?
- How to extend a readonly property ?????
- How to compute the square root of an integer?
- How to read video frames in hadoop?如何在Hadoop中读取视频帧?
- how to read openstack code : stevedore
- Please read "Security" section of the manual to find out how to run mysqld as root!错误解决