This question already has answers here:
Output single character in C
(5 answers)
Closed 8 years ago.
Hi I'm new to C and I'm having trouble finding a way of printing only the 4th, 5th or 10th letter of a String.
I've got this little code:
char firstWord[100];
char secondWord[100];
printf("Please type in: Hello World\n");
fgets(firstWord, sizeof(firstWord), stdin);
printf("Please type in: How are you?\n");
fgets(secondWord, sizeof(secondWord), stdin);
printf("You typed: %s,%s", firstWord, secondWord);
strcat(firstWord, secondWord);
printf("together it looks like this: %s", firstWord);
Now how would I print for instance the 4th or the 6th character only of the concatenated string?
A string in C is just an array of chars (with a '\0' at the end), so you can access the individual characters with an array-subscript:
printf("%c", firstWord[3]); // don't forget 4th element is at [3]
// & use %c for char
Try this
printf("%c", firstword[3]); // for 4th character
Since you're using array style char strings, you can just:
printf("%c", firstWord[3]);
For the fourth letter, and on like that. The reason it's 3 is because the array indexing starts at zero, so the first term is in the zero element, second term in the first element, etc. Then you just continue that way with all of them.
It's a lot easier if you have a pattern, though, because then you can just code a loop on the pattern, and it won't take as much effort on the coder's part.
Related
This question already has answers here:
How should character arrays be used as strings?
(4 answers)
Closed 2 months ago.
/* Variables */
int num;
char array[5]; // Array must also include NULL char
char new;
/* Accepting user input */
printf("Please enter 5 characters below:\n");
scanf("%c\r", &array[0]);
scanf("%c\r", &array[1]);
scanf("%c\r", &array[2]);
scanf("%c\r", &array[3]);
scanf("%c", &array[4]);
/* Displaying input as string */
printf("%s", array);
I am trying to create a basic program that creates a string that accepts chars one after the other. I know that arrays start at 0 and end with the null character so I made my array[5] so if I inputted "a" "b" "c" "d" "e" I would get the output string "abcde" plus the null character. Sometimes it works with one set of characters but not another. If I input "q" "w" "e" "r" "t" i might get the output "qwerta". How do I stop it from displaying that last character?
I understand that the reason why this character being displayed is that it is undefined and will show whatever value is at that memory location but I don't know how to fix it.
I have tried to include different escape sequences, putting spaces in the scanf and printf statements but what am I doing wrong?
You have a character array with size 5. You read a character into each of the five elements of the array. This does not leave space for the null character, and you do not explicitly set the last char equal to '\0'. Thus this is not a null terminated string, and printing it as a string with the %s specifier in printf has undefined behavior.
This question already has answers here:
Getting wrong string length
(3 answers)
Closed 4 years ago.
I have this piece of code:
char* input = malloc(sizeof(char)*100);
scanf("%s", input); //let's say that the number of chars in "%s" is 5
How do I calculate how many chars I typed in (5)? I tried by playing around with sizeof(), but couldn't find a solution.
Edit (better explanation): the input variable can host up to 100 chars, but let's say I type in the terminal 'abcde': then it hosts only 5 chars, the other 95 are not taken. I want to calculate that '5'.
You have to find the null terminator.
int i = 0;
while(input[i] != 0) {
++i;
}
//i marks the spot
But yeah, strlen() does a better job, since it has some improved/optimized searching, since it uses word(16/32/64? bit) compare and stuff.
I'm trying to make a simple program from C to store a data then save it to 2d array there's 2 data stored in the 2d array. I think the saving code is work well, but when I try to print out the data stored in 2d array it crashes.
Here's my code :
#include <stdio.h>
int main(){
char data[2][3];
//input the data then save it in 2d array
printf("enter the first word: ");
scanf("%s", &data[0][0]);
printf("enter the second word: ");
scanf("%s", &data[1][0]);
//here is the problem when iam trying to print out the stored data in 2d array
printf("first word: %s\nsecond word: %s", data[0][0],data[1][0]);
}
You have 3 issues with your code.
First, and the one causing your code to crash is your final printf(). You passed in data[0][0] which is of type char to %s which takes a null terminated string. You have also need an extra new line at the end. Change it to:
printf("first word: %s\nsecond word: %s\n", data[0], data[1]);
Second, your second dimension of your array is only 3. This means you can only store strings of size 3 or less. Accounting for the null terminator at the end, it's just a 2 character array. Change the second dimension to a bigger number (i.e. data[2][50]).
Third, &data[0][0] is redundant. You are dereferencing a pointer then making it a pointer again. Just do data[0] and data[1] in your scanf().
About your confusion of 2d char arrays
I think you are confused about what char arrays are and what c-strings are. A char array is an array of char. "Bill", for example, would be a char array where 'B' will be the index 0, 'l' will be index 3, and a null ternimator '\0' will be the last index to tell the machine that this is the end of the string.
A 2d char array would be an array of those strings (e.g. "Bill") like "Bill", "Bob", "Alice" etc. If you want to also keep track of not only people's names, but also their addresses, phones etc, you might need a 3d array.
The 3d array will look something like data[2][4][50]. Where the first level are the people you want to keep track of. The second level are the attribute of a specific person (name, address etc.). Third level will be an array of characters (char) that makes up an attribute about a person.
Clearing one thing...
Pass the address of a character array not the address of a char.
scanf("%s", data[1]);// same as &data[1][0]
Here you will see that the passing the address of the char variable also works because it is basically coincides with the address of the char array.
Error lies somewhere else...
Also you should pass the address of the char array to the printf.
printf("first word: %s\nsecond word: %s\n", data[0], data[1]);
Or as it is pointed out in the line before..yes you got it right..this also works
printf("first word: %s\nsecond word: %s\n", &data[0][0], &data[1][0]);
And as you know there will be 2 characters use scanf("%2s",data[1]).
So where did I do wrong?
"%s" expects a char* and what you passed to it is char. That's why it ran into error. Yes, it considered that char value to be an address and tried to access it and it invoked undefined behavior.
If you want to print characters then you will use different format specifier:
printf("%c",data[1][0]);
Few things to point out:-
You are only considering 2 length char arrays or 2 length strings.
To remind you once more %c deals with arguments of type char and %s deals with arguments of type char*. (That's why the distinction in printf).
scanf() is like a parser. In case it fails to parse something it skips it. There are better ways to get input fgets() etc.
This question already has an answer here:
Is printf()'s string width safe with unterminated strings?
(1 answer)
Closed 5 years ago.
I stumbled upon this behavior that I am curious to understand.
I mistakenly wrote the following at the end of a program to print the elements in an array of char :
printf("output: %s",outputText[]);
when I should have (and ultimately did) iterate over the array and printed each element like so:
for(int i = 0; i < textLength; i++){
printf("%c",outputText[i]);
}
What prompted me to implement the latter was the output I was getting. Despite initializing the array to limit the characters to outputText[textLength], ensuring that there were no unexpected elements in the array, my output when implementing the former code would always be littered with additional spooky elements, like below:
I've just run the same program three times in a row and got three random characters appended to the end of my array.
(Edit to replace outputText[] --> outputText in first example.)
%s is for strings; a string is a array of chars ending with NUL (0x00 in hex, or '\0' as character), so the printf() will print until it finds a NUL!
If you set the last element of the array to NUL, printf will finish there.
You are probably missing the '\0' character as the element of the character array that marks the end of the string.
You are missing string terminating character \0 end of the string. So, make your string is \0 terminated. Like:
outputText[textLength-1] = '\0';
This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 7 years ago.
char *word[128];
fgets(word, 128, stdin);
if(word == "hello")
printf("You entered hello as your word.");
So basically I am trying to get user input as a string and then use the following comparison so see if the string the user entered is equal to "hello". however, when compiling this code, it doesn't work. What did I do wrong?
EDIT: So based on feedback so far this is what I have:
char word[128];
fgets(word, 128, stdin);
if(strcmp(word, "Hello") == 0)
printf("match\n");
However, when I compile and run this program and enter Hello it does not print "match".
You need to use strcmp to compare strings.
if(strcmp(word, "Hello") == 0)
printf("match\n");
Use strcmp(char *s1, char *s2) to compare strings.
Also change char *wordto char word[].
fgets, as you used it, reads in characters from stdin until it has read new line, 127 characters or EOF (end of file). The new line is part of the string read in word and so the comparison is not equal.
To illustrate, you need to know that a C-style string is an array of characters ended by the special escape character \0. So you are comparing those two strings hello\n\0 and hello\0; note the newline character in the string read from stdin.
You can overwrite the \n at the 6th position with \0 so your strings compare to equal.
A better, general solution is to simply iterate over the characters of the string and replace the first found \n by \0; this could be a good exercise for you maybe.
== does not compare the strings the way you expect it. It merely compares the addresses of the two objects, which in this case are of course different.