I am working on a problem where I need to input a line of numbers with one or more whitespaces in between and add the numbers. But I am having a problem with ignoring the whitespaces.
I have tried using scanf(" ") and scanf("%*c").
What is the most efficient way to do so?
Thanks.
If the number of input integers in an entered string is unknown then you can use the approach shown in the demonstrative program.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
enum { N = 100 };
char line[N];
while ( fgets( line, N , stdin ) != NULL && line[0] != '\n' && line[0] != '\0' )
{
long long int sum = 0;
const char *s = line;
char *p = line;
do
{
s = p;
sum += strtol( s, &p, 10 );
} while ( s != p );
printf( "sum = %lld\n", sum );
}
return 0;
}
If to enter string
1 2 3 4 5
then the output will be
sum = 15
To read integers, use the format string %d, like this:
#include <stdio.h>
int main(void)
{
int sum, i, n;
sum = 0;
n = scanf("%d", &i);
while (n == 1) {
sum += i;
n = scanf("%d", &i);
}
printf("%d\n", sum);
return 0;
}
If you want to read real numbers, use the format string %lf (which stands for long float) and adjust the code above accordingly.
The way to do it in C++ would be
double a;
double b;
double c;
std::cin >> a >> b >> c;
I am not sure if you can do something very similar in C, please tell me if that was helpful.
Related
I am having an issue with the output of my code, which is trying to return an array backwards in c using pointers. Do you guys have any solutions to the error I am getting?
Sample input:
Please enter the array size: 3
Please enter 3 elements:
4, 5, 7
Segmentation fault (core dumped)
Code:
#include <stdio.h>
int main(void){
int size, i;
int *pointer;
int arr[size];
printf("Please enter the array size: ");
scanf("%d/n", &size);
pointer = &arr[0];
printf("Please enter %d elements: \n", size);
for(i = 0; i < size; i++){
scanf("%d", arr[i]);
pointer++;
}
pointer = &arr[size - 1];
printf("The reversed array is \n");
for(i = size; i > 0; i--){
printf("%d", arr[i]);
pointer--;
}
return 0;
}
The task is not simple for beginners like you and me.
As I have understood the user can enter any number of integers in one line and all entered integers in the line must be outputted like
You entered 2
In this case neither array nor character array nor integer array will help. And in fact you need not to define an array if you want only to output numbers stored in the input buffer.
In this case you can just use the standard function getchar. Using the function in a loop you can read all numbers placed by the user in one line in the I/O buffer.
Here is a sample program. It is a little complicated because I allow the user to enter sign symbols.
There is no check in the program whether the user entered not a digit or a sign. You can develop the program further. The program demonstrates an approach to solve the task.
#include <stdio.h>
#include <ctype.h>
int main( void )
{
const int Base = 10;
printf( "Enter a seria of integer numbers in one line: " );
int c;
int sign = 0;
int num = 0;
do
{
c = getchar();
if (c == EOF || c == '\n' )
{
if (sign)
{
printf( "You entered %d\n", num );
}
}
else if (isblank( ( unsigned char )c ))
{
if (sign)
{
printf( "You entered %d\n", num );
sign = 0;
num = 0;
}
}
else
{
if (c == '-' || c == '+')
{
if (sign)
{
printf( "You entered %d\n", num );
num = 0;
}
sign = c == '-' ? -1 : 1;
}
else if (isdigit( ( unsigned char )c ))
{
c -= '0';
if (sign == 0) sign = 1;
if (sign == 1)
{
num = Base * num + c;
}
else
{
num = Base * num - c;
}
}
}
} while (c != EOF && c != '\n');
}
The program output might look for example like
Enter a seria of integer numbers in one line: 1 -1 +12-12+13 +14 -15
You entered 1
You entered -1
You entered 12
You entered -12
You entered 13
You entered 14
You entered -15
If you want to enter several lines of numbers and output numbers that are present in each line then the program can look the following way
#include <stdio.h>
#include <ctype.h>
int main( void )
{
const int Base = 10;
size_t i = 0;
while (1)
{
printf( "Enter a seria of integer numbers in one line (or press just Enter to exit): " );
int c = getchar();
if (c == EOF || c == '\n') break;
ungetc( c, stdin );
printf( "Line %zu contains the following numbers:\n", i++ );
int sign = 0;
int num = 0;
do
{
c = getchar();
if (c == EOF || c == '\n')
{
if (sign)
{
printf( "You entered %d\n", num );
}
}
else if (isblank( ( unsigned char )c ))
{
if (sign)
{
printf( "You entered %d\n", num );
sign = 0;
num = 0;
}
}
else
{
if (c == '-' || c == '+')
{
if (sign)
{
printf( "You entered %d\n", num );
num = 0;
}
sign = c == '-' ? -1 : 1;
}
else if (isdigit( ( unsigned char )c ))
{
c -= '0';
if (sign == 0) sign = 1;
if (sign == 1)
{
num = Base * num + c;
}
else
{
num = Base * num - c;
}
}
}
} while (c != EOF && c != '\n');
putchar( '\n' );
}
}
The program output might look for example like
Enter a seria of integer numbers in one line (or press just Enter to exit): 1 -2 3 +4
Line 0 contains the following numbers:
You entered 1
You entered -2
You entered 3
You entered 4
Enter a seria of integer numbers in one line (or press just Enter to exit): 11-12 13+14
Line 1 contains the following numbers:
You entered 11
You entered -12
You entered 13
You entered 14
Enter a seria of integer numbers in one line (or press just Enter to exit):
As the program just outputs entered numbers then actually there is no need to build an object of the type int like
num = Base * num + c;
You could just output adjacent digits in a line.
int array[100];
int n;
scanf("%d", &n);
for(int i=0; i<n; i++) {
scanf("%d", &array[i]);
}
for(int i=0; i<n; i++) {
printf("You entered %d \n", array[i]);
}
We use the array to get all of the values, and just print them out at the end.
In C and C++ it does not matter if the values are separated by space or a newline, so you can get every integer in a single line if separated by spaces.
output
3
1 2 3
You entered 1
You entered 2
You entered 3
C makes this very easy, but you need to leverage some library functions. At the most simple:
use fgets() and strpbrk() to obtain and verify a line of text
use strtok() and strtol() to parse and verify integer values.
What you do with those values is up to you. Following your example prompt, let’s just print them.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int error( const char * message, const char * value )
{
fprintf( stderr, "%s%s\n", message, value );
return 1;
}
int main()
{
printf( "Input: " );
// Get all input on a single line
char text[1000];
fgets( text, sizeof(text), stdin );
// Verify that the entire line of input was obtained
char * nl = strpbrk( text, "\r\n" );
if (!nl) return error( "Line too long!", "" );
*nl = '\0';
puts( "Output:" );
// For each whitespace-delimited (spaces, tabs) token in the line:
for (char * token = strtok( text, " \t" ); token; token = strtok( NULL, " \t" ))
{
// Attempt to convert it to an integer
char * nok;
int n = strtol( token, &nok, 10 );
if (*nok) return error( "Invalid integer value: ", token );
// Success!
printf( "You entered %d\n", n );
}
return 0;
}
Notice also how it is OK to create a little helper function (error()). You can make helpers as complex or simple as you need. For this helper, all we need was to complain with one or two strings and return an “error happened” exit code that main() can pass right to the shell.
fgets can be used to read a line.
strtol can parse integers and report overflow and invalid input.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <limits.h>
int parselint ( char *line, int *value, char **end) {
long int number = 0;
errno = 0;
number = strtol ( line, end, 10);
if ( *end == line) {// nothing was parsed. no digits
size_t span = strcspn ( *end, "-+0123456789"); // characters to next int
if ( ! span) {
span = 1;
}
fprintf ( stderr, "problem parsing: %.*s\n", (int)span, line);
*end += span; // advance pointer to next int
return 0;// return failure
}
if ( ( errno == ERANGE && ( number == LONG_MAX || number == LONG_MIN))
|| ( errno != 0 && number == 0)) {// parsing error from strtol
fprintf ( stderr, "problem %.*s", (int)(*end - line), line);
perror ( " ");
return 0;
}
if ( number > INT_MAX || number < INT_MIN) {
fprintf ( stderr, "problem %.*s ", (int)(*end - line), line);
fprintf ( stderr, "out of int range\n");
return 0;
}
*value = number;//assign number to pointer
return 1;//success
}
int main ( void) {
char line[4096] = "";
char *parse = line;
int number = 0;
fgets ( line, sizeof line, stdin);
line[strcspn ( line, "\r\n")] = 0; // remove newline
while ( *parse) {
if ( 1 == parselint ( parse, &number, &parse)) {
printf ( "you entered %d\n", number);
}
}
return 0;
}
This is one of the assignments for my class and this is the objective of the assignment:
Write a program whose input is a character and a string, and whose output indicates the number of times the character appears in the string. The output should include the input character and use the plural form, n's, if the number of times the characters appears is not exactly 1. You may assume that the string does not contain spaces and will always contain less than 50 characters.
This is the code I have so far and I am new to C programming so I don't know how to declare Strings correctly just yet. So far I learned there are no strings in C like there is in Java and you have to do them as a character array:
#include <stdio.h>
#include <string.h>
int main(void) {
char userChar;
char userString[50];
int count = 0;
for (int i = 0; i < userChar; i++) {
if (userString[i] == userChar)
count++;
}
printf("%d", count);
if (count != 1)
printf("'s");
return 0;
}
For example, if I wanted to input n Monday and output 1 n
What would I need to change in my code to go from n Monday to 1 n
This is the only output I am getting, and it only has outputted one thing correctly:
0's
First, I hope this is not considered cheating :-)
Second, you need to define userChar and userString as arguments for main, and pass them in at run time. They are assigned nothing, so that is why you get
0's
Third, your for condition is wrong. You need this so it only iterates through the length of the string:
for (int i = 0; i < strlen(userString); i++)
Finally, You are not printing the value of userChar prior to the return
At first you need to input a string and a character. To count the number of occurrences of the character in the string you can use standard string function strchr.
The program can look something like the following
#include <stdio.h>
#include <string.h>
int main(void)
{
char userChar = ' ';
char userString[50] = "";
printf( "Enter a string without embedded spaces\nof the length less than %d: ", 50 );
scanf( "%49s", userString );
printf( "Enter a character to search in the string: " );
scanf( " %c", &userChar );
size_t n = 0;
for ( const char *p = userString; ( p = strchr( p, userChar ) ) != NULL; ++p )
{
++n;
}
printf( "%zu%s %c\n", n, n < 2 ? "" : "'s", userChar );
}
The expected output is not 0's, it should include the counted character: for example if the character is n and the string Monday, the output should be
1 n
and if the string is Eeny-meeny-miny-moe, the output would be
3 n's
Here is a modified version:
#include <stdio.h>
int main() {
char userChar;
char userString[50];
int i, count;
printf("Enter character: ");
scanf(" %c", &userChar);
printf("Enter string (single word): ");
// read a word with at most 49 characters
scanf(" %49s", userString);
count = 0;
for (i = 0; userString[i] != '\0'; i++) {
if (userString[i] == userChar)
count++;
}
printf("%d %c", count, userChar);
if (count != 1)
printf("'s");
printf("\n");
return 0;
}
There is a question: I should scan a number with 300 digits and print the sum the digits but I cant scan it with long long int and I dont know what to do.
You can scan the number as a string with fgets() or simply read one byte at a time with getchar():
#include <stdio.h>
int main() {
int c;
int sum = 0;
while ((c = getchar()) != EOF) {
if (c >= '0' && c <= '9')
sum += c - '0';
else
break;
}
printf("sum: %d\n", sum);
return 0;
}
I you must use scanf(), here is an alternative:
#include <stdio.h>
int main() {
char buf[2];
int sum = 0;
while (scanf("%1[0-9]", buf) == 1) {
sum += *buf - '0';
}
printf("sum: %d\n", sum);
return 0;
}
#include <stdio.h>
int main()
{
char digit;
int sum = 0;
while ( scanf("%c", &digit) != EOF)
{
sum += digit - '0';
}
printf("sum: %d\n", sum);
return 0;
}
The most straight forward solution seems to be to repeatedly read in 1-digit ints and sum them up while that works.
One digit numbers can easily be read into an int (no long needed) and even the sum of 300 digits will not exceed an int.
#include <stdio.h>
int main()
{
int digit=0;
int sum=0;
while(1==scanf("%1d",&digit))sum+=digit;
printf("sum:%d\n", sum);
return 0;
}
This admittedly (thanks chqrlie for pointing out) expect an end of line, as it comes with e.g. test input at online compilers or judges. In an interactive prompt
... a single line of digit will not suffice, an explicit end of file with ^D is needed.
In such a case you need to enter a number as a string.
To enter a number you should use the standard function fgets. The corresponding character array must have 302 characters: 300 characters for digits, one character for the new line character '\n' that is appended by the function fgets to the entered string and one character for the terminating zero character '\0' of the string.
If the new line character '\n' is not present in the string it means that the user entered more than 300 characters.
Also the user can enter a number with leading or trailing spaces.
You need to check that the entered string contains a valid number.
Here is a demonstration program.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int is_valid_number( const char *number )
{
while ( isblank( ( unsigned char )*number ) ) ++number;
int valid = *number != '\0';
if ( valid )
{
while ( isdigit( ( unsigned char )*number ) ) ++number;
while ( isblank( ( unsigned char )*number ) ) ++number;
valid = *number == '\0';
}
return valid;
}
int main( void )
{
enum { N = 300 };
char number[N + 2] = { 0 };
printf( "Enter a non-negative number (no greater than %d digits): ", N );
fgets( number, sizeof( number ), stdin );
int valid = strchr( number, '\n' ) != NULL;
char *p = number;
if ( valid )
{
number[ strcspn( number, "\n" ) ] = '\0';
while ( isblank( ( unsigned char )*p ) ) ++p;
valid = is_valid_number( p );
}
if ( !valid )
{
puts( "Invalid number." );
}
else
{
unsigned int sum = 0;
for ( char *digit = p; isdigit( ( unsigned char )*digit ); ++digit )
{
sum += *digit - '0';
}
printf( "The sum of digits = %u\n", sum );
}
}
Its output might look like
Enter a non-negative number (no greater than 300 digits): 1234567890123456789012345678901234567890
The sum of digits = 180
you can use char to scan each digit. also in this way you do not need string.enter image description here
I am pretty new in C and I have a question about scanf just for digits. What I need to do is scanf in input just 3 digits, antoher characters or symbols should be evaluate as trash. Or maybe I need use isdigit() but I am not sure how it works. I have just that, but I know that it doesn't work:
scanf("%d, %d, %d", &z, &x, &y);
You could read a string, use a scan set to filter it and convert it to an integer.
See scanf: http://www.cplusplus.com/reference/clibrary/cstdio/sscanf/
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char num1[256], num2[256], num3[256];
scanf("%s %s %s", num1, num2, num3);
sscanf(num1, num2, num3, "%[0-9]d %[0-9]d %[0-9]d", num1, num2, num3);
int n1 = atoi(num1), n2 = atoi(num2), n3 = atoi(num3); // convert the strings to int
printf("\n%d %d %d\n", n1, n2, n3);
return 0;
}
Sample Input & Output:
2332jbjjjh 7ssd 100
2332 7 100
A little more complicated solution, but prevents overflow of array and works for any kind of input. get_numbers_from_input function takes array where read numbers will be put and maximum count of numbers in array and returns count of numbers read from standard input. function reads characters from standard input until enter is pressed.
#include <stdio.h>
//return number readed from standard input
//numbers are populated into numbers array
int get_numbers_from_input(int numbers[], int maxNumbers) {
int count = -1;
char c = 0;
char digitFound = 0;
while ((c = getc(stdin)) != '\n') {
if (c >= '0' && c <= '9') {
if (!digitFound) {
if (count == maxNumbers) {
break; //prevent overflow!
}
numbers[++count] = (c - '0');
digitFound = 1;
}
else {
numbers[count] = numbers[count] * 10 + (c - '0');
}
}
else if (digitFound) {
digitFound = 0;
}
}
return count + 1; //because count starts from -1
}
int main(int argc, char* argv[])
{
int numbers[100]; //max 100 numbers!
int numbersCount = get_numbers_from_input(numbers, 100);
//output all numbers from input
for (int c = 0; c < numbersCount; ++c) {
printf("%d ", numbers[c]);
}
return 0;
}
Try this.
If the first char is not a digit.
Use "%*[^0-9]" to skip chars which is not digits.
' * ' is an optional starting asterisk indicates that the data is to be read from the stream but ignored (i.e. it is not stored in the location pointed by an argument), and ' ^ ' means any number of characters none of them specified as characters between the brackets.
#include <stdio.h>
int main()
{
int x,y,z;
if(!scanf("%d",&x)==1) scanf("%*[^0-9] %d",&x);
if(!scanf("%d",&y)==1) scanf("%*[^0-9] %d",&y);
if(!scanf("%d",&z)==1) scanf("%*[^0-9] %d",&z);
printf("%d %d %d\n",x,y,z);
return 0;
}
Input & Output
fehwih 2738 #$!(#)12[3]
2738 12 3
Reference from: http://www.cplusplus.com/reference/cstdio/scanf/
I want to read numbers(integer type) separated by spaces using scanf() function.
I have read the following:
C, reading multiple numbers from single input line (scanf?)
how to read scanf with spaces
It doesn't help me much.
How can I read numbers with space as delimiter. For e.g. I have following numbers as input 2 5 7 4 3 8 18 now I want to store these in different variables.
Please help.
I think by default values read by scanf with space/enter. Well you can provide space between '%d' if you are printing integers. Also same for other cases.
scanf("%d %d %d", &var1, &var2, &var3);
Similarly if you want to read comma separated values use :
scanf("%d,%d,%d", &var1, &var2, &var3);
scanf uses any whitespace as a delimiter, so if you just say scanf("%d", &var) it will skip any whitespace and then read an integer (digits up to the next non-digit) and nothing more.
Note that whitespace is any whitespace -- spaces, tabs, newlines, or carriage returns. Any of those are whitespace and any one or more of them will serve to delimit successive integers.
int main()
{
char string[200];
int g,a,i,G[20],A[20],met;
gets(string);
g=convert_input(G,string);
for(i=0;i<=g;i++)
printf("\n%d>>%d",i,G[i]);
return 0;
}
int convert_input(int K[],char string[200])
{
int j=0,i=0,temp=0;
while(string[i]!='\0')
{
temp=0;
while(string[i]!=' ' && string[i]!='\0')
temp=temp*10 + (string[i++]-'0') ;
if(string[i]==' ')
i++;
K[j++]=temp;
}
return j-1;
}
It should be as simple as using a list of receiving variables:
scanf("%i %i %i", &var1, &var2, &var3);
With this solution, it's possible to read positive and negatives integers:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 50
int convert_input (int * v, char * buffer) {
int len = 0, i = 0, temp = 0, positive_or_negative_one = 1;
while(buffer[i]!='\0') {
temp = 0;
if (buffer[i] == '-'){
positive_or_negative_one = -1;
i++;
} else {
while(buffer[i] != ' ' && buffer[i] != '\0')
temp = temp*10 + (buffer[i++]-'0');
if(buffer[i]==' ')
i++;
v[len++] = temp * positive_or_negative_one;
positive_or_negative_one = 1;
}
}
return len;
}
int main(int argc, char const *argv[]) {
int *a = NULL;
int count_a, len=0;
char buffer[BUFFER_SIZE];
printf("Input numbers here: ");
gets(buffer);
for (int i = 0; i < strlen(buffer); i++) {
if (buffer[i] == ' '){
len+=1;
}
}
a = (int*) malloc(sizeof(int) * len + 1);
count_a = convert_input(a, buffer);
for (int i = 0; i < count_a; i++) {
printf("%d\n", a[i]);
}
free(a);
return 0;
}
Input and output example:
Input numbers here: 1 2 3 -4 10
1
2
3
-4
10