I read chars until '\n', convert them to int and sum the numbers until the result is only one digit.
I can't use mod or .
The first run went well, but the second one keep running and not waiting to \n.
any reason for keeping the '\n'?
#include<stdio.h>
int main(){
char str[8], conv_str[8],c;
int i,val,ans = 0;
while(1){
printf("Enter 8 values(0-9) :\n");
scanf("%[^\n]", str); // Scan values to str untill \n
for(i = 0;i < 8;i++){
val = str[i]-48; //convert from asci to int
ans += val;
}
while(ans > 9){
// itoa convert int to string, str(the input) is the buffer and 10 is the base
itoa(ans,conv_str,10);
ans = (conv_str[0]-48) + (conv_str[1]-48) ;
}
printf("the digit is: %d", ans);
printf("\ncontinue? (y/n)\n");
scanf("%s", &c);
if (c == 'n')
break;
memset(str, 0, sizeof(str));
}
return 0;
}
TIA
You have multiple problems in the code. Some of them are
scanf("%s", &c); is wrong. c is a char, you must use %c conversion specifier for that.
You never checked for the return value of scanf() calls to ensure success.
While scanning for character input, you did not clear the buffer of any existing inputs. Any existing character, including a newline ('\n') already present in the buffer will be considered as a valid input for %c. You need to clear the buffer before you read a character input.
Related
Is there a simple way to make sure you're reading a character through scanf. If it were an integer I'd use a do while loop
do{
printf("enter a number");
fehler = scanf(" %d", &x);
getchar();
} while(fehler!=1);
But I'm not fully sure what to do if the input is meant to be a string. I know the alphabets are stored as ASCII values but the if constraints in the while statement don't seem to be working(unless I'm doing it wrong)
char * temp2;
temp2 = malloc(sizeof(string));
do{
printf("PLease enter a string: ");
scanf(" %s", temp2);
getchar();
} while(temp2 <= 'A' && temp2 <= 'z')
You can't compare a string to a single character. You have to loop through the entire string, checking every character.
#include <ctype.h>
int is_alphabetic(char *str) {
for (int i = 0; str[i]; i++) {
if (!isalpha(str[i])) {
return 0;
}
}
return 1;
}
...
do{
printf("Please enter an alphabetic string: ");
scanf(" %s", temp2);
getchar();
} while(!is_alphabetic(temp2));
You see printf and scanf work independently. Whatever you store be it a character or number is stored in form of a number. Now it depends on the printf function what it demands.
Eg.: If you store 'a' at a location, the number 97 is stored. Now if you print a number it prints 97 and if you demand a character it gives a.
#include <stdio.h>
int main()
{
int i = 97;
printf("%d \n", i);
printf("%c", i);
return 0;
}
See the results. Further char, int , long int are just data types which specify the number of bits that would be resrved for the inputs for the variable.
Execute this program and you'll understand:
#include <stdio.h>
int main()
{
int i;
for (i=97; i <=200 ; i++)
{
printf("%d %c,\t",i,i);
};
return 0;}
This will show you a nmber when printed as a number and then the SAME number read as character.
Note there are no markers in memory to store which type of data it is. It is straightforward stored as number.
scanf is absolutely the wrong tool for this. But if you want to read only alphabetic characters, you can do it easily enough with something like:
char s[32];
if( 1 == scanf(" %31[a-zA-Z]", s) ){ ... }
The %31[a-zA-Z] conversion specifier will match only the literal characters a thru z and A thru Z, and will only consume up to 31 characters of input. You must always use a field width modifier with %s or %[] conversion specifiers to avoid an overflow.
I'm trying to make a program which returns the a number and a string with the elements in reverse order. I was able to do both, but I don't understand why there are some blank new lines when I print out the reversed string
I've also tried it with just a single word using the scanf function, and a blank line still appears
#include <stdio.h>
#include <stdlib.h>
int main()
{
char s[50];
int i, n, lastDigit, textLen=0;
printf("Enter a number: ");
scanf("%i", &n);
getchar();
printf("Enter the text: ");
fgets(s, 50, stdin);
printf("The reversed number is: ");
while(n > 0){
lastDigit = n%10;
n=n/10;
printf("\n%i", lastDigit);
}
printf("\nThe reversed text is: ");
while(s[textLen] != '\0'){
textLen++;
}
for(i=textLen; i>=0; i--){
printf("\n%c", s[i]);
}
return 0;
}
I expect:
T
e
s
t
But the actual output is:
T
e
s
t
From the manual page of fgets
fgets() reads in at most one less than size characters from stream
and stores them into the buffer pointed to by s. Reading stops after
an EOF or a newline. If a newline is read, it is stored into the
buffer.
So here
char s[50];
fgets(s, 50, stdin);
fgets() stores the newline character at the end of buffer s if it was read. To remove this trailing \n character use strcspn(). For e.g
char s[50] = {}; /* Initialize it */
fgets(s, 50, stdin);
s[strcspn(s, "\n")] = 0; /* remove the trailing \n */
textLen is the number of characters in string s. The first character printed is s[textLen], which is the NUL character at the end.
Ive got this program which im stuck with in which I am trying to receive the size of a string and following it, telling the user to input the letter by letter. Here is my code.
#include<stdio.h>
#include<stdlib.h>
int main(){
int size;
int i;
char letter;
printf("Your string's size is...?: ");
scanf("%d", &size);
char mystring[size] ;
for (i=0; i<size; i++){
printf("Write a letter: \n");
scanf("%c", &letter);
mystring[i] = letter;
}
printf("%s",mystring);
system("PAUSE");
return 0;
}
Thanks!
Two problems here.
First, the %c format specifier to scanf will read any character, including a newline. You need to put a space before it to absorb any newlines in the input buffer:
scanf(" %c", &letter);
Second, you don't null-terminate the string, nor do you leave enough space in the array to store the null terminator. Make the array one element larger, and add the null byte at the end:
char mystring[size+1];
for (i=0; i<size; i++){
...
}
mystring[size] = 0;
Two things:
First, you need to terminate the string with a \0-character. Otherwise, printf will result in undefined behaviour.
Second, note that scanf("%c",..) will probably consume a new line left in the buffer when a user presses "enter" after having entered a number (i.e. the size).
Write:
char mystring[size+1] ;
for (i=0; i<size; i++){
printf("Write a letter: \n");
scanf("%c", &letter);
if (i==0 && letter == '\n') {
i--;
continue;
}
mystring[i] = letter;
}
mystring[size] = '\0';
printf("%s",mystring);
How can I read six digits separately, and then append them?
For example:
I want to enter the following digits: 2 3 6 , 7 5
And the expected output would be: "236,75".
I have to do it with only one loop (to read the numbers), and I have to read the numbers with the type char.
Here's what I have so far:
#include <stdio.h>
int main()
{
char c;
char string [6];
printf("Introduce a number\n");
int i = 0;
while (i <=5) {
scanf("%c", &c);
string[i] = c;
i++;
}
printf("%c\n",string);
}
Try something like this:
char string [7];
printf("Introduce a number\n");
int i = 0;
while(i <=5){
scanf("%c", &c);
string[i] = c;
i++;
}
string[i] = '\0';
//printf("%s", string);
I added the '\0' character at string[6], just in case you need that for printing the values for example.
Also, I recommend you to read about cleaning the input buffer when obtaining input from stdin. Hope it helps.
For starters ensure that your int main() is actually returning an integer.
#include <stdio.h>
int main()
{
char c;
char string[7];
char* stringy = string;
printf("Introduce a number\n");
int i = 0;
while (i <=5) {
scanf("%c", &c);
string[i] = c;
i++;
}
string[i] = '\0';
printf("%s\n",stringy);
return 0;
}
Also you want to print your entire string out with a %s format specifier. This also means that you'll need to null terminate your string which can be done by setting the last character in your array to \0.
Also make sure your array has 7 indexes instead of 6, so everything can fit.
#include <stdio.h>
int main()
{
char c;
char string [7];
printf("Introduce a number\n");
int i = 0;
while (i <=5) {
scanf("%c\n", &c);
string[i] = c;
i++;
}
string[i] = '\0';
printf("result: %s\n",string);
return 0;
}
C strings end with a null character, that is '\0'. Therefore you should always append the null character to a character string as the last character since it determines the end of the string. Therefore the line string[i] = '\0'; is necessary (at the end of the while loop, the value of i will be 6, thus pointing to the last element of the character array).
Another correction to your code is the final printf(). You specified the format to be character format ("%c"), which will only output the first character of the string. You should change it to "%s" for printing the whole string.
This program should work since it is a valid C code. If you are having troubles with this code, then it is platform specific. I couldn't run this code on VS2012, but managed to run it on a GNU C Compiler. Try running the code on an online C compiler, it should work just fine.
/*
Program to calculate trip and plan flights
*/
#define TRIP 6
#define DEST 1
#include <stdio.h>
int error_dest(int type_num, int cont_num, int dest_code, int check);
int main(void)
{
int check, type_num, cont_num, index, i, dest_code, trip_num, row, col;
int travelint[TRIP][DEST], travelarea[TRIP];
char area_code, S, M, L, N, P, K, R, C, U, W, O;
trip_num = 7;
while (trip_num > TRIP)
{
printf("Please enter the number of trips:");
scanf("%d", &trip_num);
if ( trip_num < TRIP)
{
printf("Valid trip number. Please proceed to enter destination code.\n");
}
else
{
printf("Invalid trips. Please enter no more then 6 trips.\n");
}
}
/*********************************************************************************/
for (i=0; i < trip_num ; i++) /*destination code input*/
{
printf("Please enter destination code:");
scanf("%d", &dest_code); /*input of destination code*/
check = error_dest(type_num, cont_num, dest_code, check);
if (check == 2)
{ travelint[i][0]=dest_code; }
else
{
while (check == 1)
{
printf("Please enter destination code:");
scanf("%d", &dest_code); /*input of destination code*/
check = error_dest(type_num, cont_num, dest_code, check);
if (check == 2)
{ travelint[i][0]=dest_code; }
}
}
printf("Please select from the following that best describes your destination:\n");
printf("S Small city - population under 50,000\n");
printf("M Medium city - population between 50,000 and 500,000\n");
printf("L Large city - pop. over 500,000\n");
printf("N Natural formation like a mountain, a lake, a cave, a geyser, a fjord, a canyon, etc.\n");
printf("P Designated park or reserve such as a wildlife refuge, a national park, a bioreserve, or a protected marine area\n");
printf("K Man made landmark like the Great Wall of China, the Taj Mahal, or Stonehenge\n");
printf("R State or province or region of a country\n");
printf("C Whole country\n");
printf("U Multiple countries like traveling through Europe\n");
printf("W Ocean voyage\n");
printf("O Any other type of destination - such as visiting the sites of the seven wonders of the world\n");
printf("Please enter the Area Letter code:");
scanf("%c", &area_code);
}
/*******************************************************************************/
/*print for destination_code*/
for (row = 0; row < trip_num; row++)
{
for (col=0; col < DEST; col++)
printf("Trip[%d] = %d\n", row+1, travelint[row][col]);
}
return 0;
}
error_dest(type_num, cont_num, dest_code, check)
{
cont_num = dest_code / 10000; /*math for error check*/
type_num = dest_code/1000 - cont_num*10;
if ( (cont_num <= 7) && (cont_num > 0) && (type_num <= 5) && (type_num >=0) )
{ /* loop for checking destination code*/
check = 2 ;
return check;
}
else
{
printf("%d is a invalid code\n", dest_code);
check = 1;
return check;
}
}
for some strange reason at the scanf("%c", &area_code); it just runs ahead and print the dest_code array without letting me input any character and I'm not sure what exactly I am doing wrong.
If you're looking to grab only one character, perhaps it would be better to use getchar() instead of scanf()?
Basically what's happening is this: you print the "Please enter the number of trips" message to the screen. The user types in 4 and then hits the enter key, which means the stdin buffer looks like this: "4\n". You then call scanf with the "%d" format string. scanf looks at the stdin buffer, and sees the 4. It looks at the next character, which is the newline, and sees it's not part of a number (as %d specifies), so it is done fulfilling the format string and leaves the file pointer at the newline. It converts the char '4' to an integer 4 and places it in trip_num and returns.
The next time you call scanf, it picks up where it left off at the newline. The format string this time is "%c", so it just grabs the next character from the buffer which is currently the newline ("\n"), places it in dest_code, and returns. If you want the scanf function to skip over the whitespace in this case, you have to explicitly tell it by adding a space before the "%c" format for the second scanf (destination code). Then scanf will skip over all whitespace (including that newline) until it encounters a non-whitespace character that it places in dest_code.
TL;DR: Change the second scanf call to scanf(" %c", &dest_code). And fix the other errors others have pointed out so other bugs won't manifest.
You may print area_code after scanf, I guess it may be '\n' which is the last character of the dest_code line you entered.
You should empty the buffer before reading a character from stdin:
int c = 0;
while (c != '\n' && c != EOF)
{
c = getchar();
}
then you can read your character using scanf or replace it with getchar.
This may or may not help, but previously stated you probably need to put the getchar() into the while loop. You may also need the fgets to grab the stdin from the keyboard.
while(1){
printf("Enter Message Type:");
fflush(stdout) ;
// scan msg.hdr from received message.
scanf("%d", &(msg.m_hdr));
while(getchar() != '\n'){}
printf("Enter your Message:");
fflush(stdout);
// grab data from keyboard
fgets(msg.m_data, sizeof(msg.m_data), stdin);
Use "fflush(stdin)" before you enter the character, i.e. before the "printf" statement for the character. It will flush out the input buffer and thus you can scan the desired character. Or simply give a Space before the "%c" command. Like---------- scanf(" %c", &area_code); ---------------