I am new to C and I have to write a loop that prints a number in words from a given integer between 0 and 9. And the loop should stop if the input is equal to '#'.
Exemple:
input: 1
output: ONE
#include <stdlib.h>
#include <stdio.h>
void main() {
char tableau[10][5] = {"ZERO","ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE"};
char nb[1];
while (nb[0] != '#') {
printf("nb = ");
scanf("%c", &nb[0]);
printf("%s\n", tableau[atoi(nb)]);
}
}
returns
nb = 5
FIVE
nb = ZERO
nb =
The expected output should be:
nb = 5
Five
nb =
Everything works except the line "nb = ZERO" shouldn't be there.
When the scanf line asked for input, you typed in 5<enter>, right?
So first it processed the 5, correctly, and gave output FIVE.
Then it processed the <enter> (which is character #13)
atoi(<enter>) returns 0. So it printed out ZERO.
Related
I recently encountered with an interview question. I did not understand the behaviour of printf function in this case
#include <stdio.h>
int main() {
int k = printf("String");
printf("%d",k);
}
Expected result : Compilation Error
Output : String6
Why is the output String6?
Here is the prototype for printf:
int printf(const char *format, ...);
We can see that printf returns an int.
The documentation indicates that:
Upon successful return, these functions return the number of
characters printed (excluding the null byte used to end output to
strings).
You asked why the output is "String6". Well:
printf("String");
This first prints String but does not print a newline character. Since String is 6 characters, printf returns 6, which you store in k:
printf("%d",k);
This then prints 6 (on the same line).
Try running this program:
#include <stdio.h>
int main(void)
{
int bytes_printed = printf("%s\n", "String");
// 7 = 1 + 6
printf("printf returned: %d\n", bytes_printed);
return 0;
}
Output:
String
printf returned: 7
the printf() function returns the number of character it printed. Since you set int k = printf("String");, the print function is executing printing out "String" and setting k equal to 6 since "String" is 6 characters long, then your second call to printf prints the value of k which is 6, resulting in the console displaying "String6".
This is perfectly valid C syntax.
I've been trying to read a txt which has a specific structure:
The first line indicates the n-1 lines the whole txt file has.
All the other lines have the "structure" of a card (it's number and it's pattern).
ex: I have a txt which stores 13 cards, so the file in itself has 14 lines:
13
A T
2 P
3 D
13 P
2 P
4 C
8 D
11 T
8 C
9 C
10 T
9 T
7 P
(Note: T stands for clubs, D for diamonds, C for hearts and P for spades, it's in spanish).
I've tried extracting the first line to then create a dynamic array with the number given so that I can store each line in that array, but I fail to get the first value.
My code is:
#include <stdio.h>
#include <stdlib.h>
int leerLinea(){
char contenido[1];
FILE* pArchivo;
pArchivo = fopen("Mazo.txt","r");
if (pArchivo == NULL){
printf("No hay nada aqui!\n");
return 0;
}
else{
fgets(contenido,3,pArchivo);
printf("%s\n", contenido);
}
fclose(pArchivo);
return contenido[0];
}
int main(){
int a;
a = leerLinea();
printf("a's value is: %d\n",a);
return 0;
}
But when I run it I get:
13
a's value is: 49
Why is it returning other value, when it should be returning 13?
With fgets(contenido,3,pArchivo), you read in a string into a buffer that is to small for capturing at least 2 digits and the string termination character; For that statement, it should be at least char contenido[3].
The main issue is, however, that you mix strings with "pure" integral values, i.e. you read in a string but expect it to be converted correctly to a number simply by accessing the first digit of that string; Note that if contenido containded "13", contenido[0] would give character value '1', which in ASCII is 49.
To overcome this, read in the value as a number, i.e. using "%d"-format:
int leerLinea(){
int contenido = 0;
FILE* pArchivo;
pArchivo = fopen("Mazo.txt","r");
if (pArchivo == NULL){
printf("No hay nada aqui!\n");
return 0;
}
else{
fscanf(pArchivo,"%d",&contenido);
printf("%d\n", contenido);
}
fclose(pArchivo);
return contenido;
}
1 - Read a line of text with sufficient space for each character in the line, the line-feed and a null character. The below is 4 characters, so a buffer of 6 is needed.
13 P
Further, there is little gained by being so stingy with line buffers. Suggest 2x the maximize anticipated size to allow for some growth, leading/trailing whitespace.
#define LINE_MAX (4 + 1 + 1)
char contenido[LINE_MAX * 2];
2 - When reading a line, do not hard code in the 3, use sizeof() for consistent, easier to maintain code.
// fgets(contenido,3,pArchivo);
fgets(contenido, sizeof contenido, pArchivo);
3 - Rather than return the first character of a string (the code for the character '1' is 49), convert the string into an int/long with strtol() or atol(), etc. #Nicolas Guerin
// return contenido[0];
return atoi(contenido);
// or
return strtol(contenido, NULL, 10); // better
return atoi(contenido[0]);
The probleme you've got is that you return a char in an int function, every char as an integer value. That's true but not the decimal value of the char, the ascii value.
Atoi convert a char into an int.
ps: the way you do, it will only return 1 in the exemple
so im trying to get input from a user then put the input into a array and then clear the input so it can get more but all i get is these weird symbols here is my code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char source[] = "this is the source string";
int main()
{
char people[5][260];
char input[260];
int i, l;
printf("please enter 5 names\n");
for(i=1;i<6;i++)
{
gets(input);
strcpy(people[1], input);
input[260] = '\0';
}
for(l=0;l<6;l++)
printf("%s\n", people[l]);
}
}
Change
for(i=1;i<6;i++)
{
gets(input);
strcpy(people[1], input);
input[260] = '\0';
}
to
for(i=0;i<5;i++)
{
gets(input);
strcpy(people[i], input);
input[0] = '\0';
}
Now to be clear i changed the loop from 0 to 5 instead of 1 to 6 because
array indices start from 0.
In the strcpy function call you passed the same value again and again which is 1, I changed it to the loop variable i, which is the correct way.
In your code snippet you assigned the value of input[260] = '\0' which is also wrong.
'\0' is used to denote the end of a string
so as you have to empty your character array so
'\0' should be assigned to the first index of the array to denote that
the array is empty.
Now in the second loop, since you have stored 5 names so the loop should be from i=0 to i<5 instead of i<6
So change
for(l=0;l<6;l++)
printf("%s\n", people[l]);
to
for(l=0;l<5;l++)
printf("%s\n", people[l]);
And also you used an extra curly brace after the last printf statement. Remove it and your code is fixed.
Since you have used the return type of the main function as int
int main()
So it would return an integer value, so
you should use a return statement
before the last curly brace like this
return 0;
You have declared a character array named source[] with a global scope but you haven't used it anywhere in your code so it's better if you remove it.
And also properly
indent your code using white spaces and tabs to make it understandable
and readable
, with code indentation your code will be more readable and you won't miss any curly brace or use extra ones like you used in your code.
To sum up your new code will look like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char people[5][260];
char input[260];
int i, l;
printf("please enter 5 names\n");
for(i=0;i<5;i++)
{
gets(input);
strcpy(people[i], input);
input[0] = '\0';
}
for(l=0;l<5;l++)
printf("%s\n", people[l]);
return 0;
}
The first for loop should go from 0 to 5, not 1 to 6.
Pretty sure you meant to put i in the brackets here, not 1:
strcpy(people[1], input);
Don't use gets or strcpy; they're insecure. Use fgets and strlcpy or strncpy instead.
input[260] should be input[259]; element 260 is out of bounds.
Set input[259] to zero before you copy the string, not after.
The second loop goes from 0 to 6. Again it should go from 0 to 5, since 5 is the maximum allowed index of an array of size 6.
I'm reading a text file using getchar() and I'm need to print all the integers in a file. If the file looks like:
hello 42 world
I know how to find single digit integers because getchar() gives me the ascii value of each character in the file so I need to look for values between 48 and 57 (ascii values for 0-9) but I can't figure out how to do this for n digits. In the example above I would find the values 52 and 50 for "42" but how can I turn that into 42?
I thought about creating a char array and when I find a digit put it in the array and then use atoi() to convert the string to an int but it feels like a bad solution, if it would even work.
Gene's approach packed in a program:
#include <stdio.h>
#include <ctype.h>
main()
{
int ch;
do
{
int val = 0, digits = 0;
while (isdigit(ch = getchar())) ++digits, val = 10 * val + (ch - '0');
if (digits) printf("%d\n", val);
} while (ch != EOF);
return 0;
}
So I've got this string in a C code i got from a book which has a quote in it, followed by another string which has one word from that quote. When it tell the program to find the position of the substring, it starts counting from the number 1 and not 0. Why is this? Here is what i mean:
#include <stdio.h>
#include <string.h>
int main()
{
char str[]="No Time like the Present";
char sub[]="Time";
if (strstr(str, sub)== NULL)
{
printf("not found");
}
else
{
printf("Index number found at %d",strstr(str,sub)-str);
}
return 0
}
So it'll say:
Index found at number 3
But shouldn't it be printing index found at number 2, because you start from zero? Or can you sometimes start from the number 1??!
No, it starts at zero:
No Time...
^^^^
0123
Yes it always starts at 0, space is also counted as a character here so output is 3 and not 2.
Do not confuse index and length. Index and length are different.
char[] str = "stackoverflow";
Length of str will return 13.
Index of 'c' in str will return 3.