Question mark at end of printf - c

Here is a simple code of reversing the string in C the last printf statement prints the reverse order , but with a question mark at the end, while I just want to print the reversed string not the question mark
How do I fix it?
#include<stdio.h>
#include<string.h>
int main(){
char new_string[100];
char string[100];
scanf("%s",string);
printf("original_number = %s\n",string);
int i;
int l = strlen(string)-1;
for(i = 0; i<=l; i++){
new_string[i] = string[l-i];
printf("%c\n",new_string[i]);
}
printf("rev_number = %s\n",new_string);
}
input : abcd
output:
original_number = abcd
d
c
b
a
rev_number = dcba?

You need to null terminate your string.
Add this line at after the for loop where you reverse string.
new_string[i]='\0';
for(i = 0; i<=l; i++){
new_string[i] = string[l-i];
printf("%c\n",new_string[i]);
}
new_string[i]='\0'; // add this
printf("rev_number = %s\n",new_string);
check-here

terminate new_string by new_string[i]='\0' after for-loop

If the question is "How to add '?' to the end of string?" I have to answers:
1) use strcat to add one more character, e.g.:
#include<stdio.h>
#include<string.h>
int main(){
char new_string[101] = {0}; // +1 to be sure that enough place for '?' will be available
// {0} to init empty string
char string[100];
scanf("%s", string);
printf("original_number = %s\n", string);
int i;
int l = strlen(string) - 1;
for (i = 0; i <= l; i++){
new_string[i] = string[l - i];
printf("%c\n", new_string[i]);
}
strcat(new_string, "?");
printf("rev_number = %s\n", new_string);
}
2) put ? and add character \0 after the loop end, e.g.:
#include<stdio.h>
#include<string.h>
int main(){
char new_string[101]; // +1 to be sure in place for '?'
char string[100];
scanf("%s", string);
printf("original_number = %s\n", string);
int i;
int l = strlen(string) - 1;
for (i = 0; i <= l; i++){
new_string[i] = string[l - i];
printf("%c\n", new_string[i]);
}
// add one more char
new_string[i] = '?';
// set the string end
new_string[i + 1] = '\0';
printf("rev_number = %s\n", new_string);
}
Pay attention, that if you fill all the array with 0 as char new_string[101] = {0};, you do not need to add end of string with new_string[i + 1] = '\0';, so the second variant can be shorter if initialization is as in the first one
For both snippets I have the same output
UPDATE:
One more advice on working with strings. When input is made with scanf and you know how much characters can be stored in your array of chars use the following approach to prevent violation of the array boundaries
char string[10]; // if you have 10 bytes
scanf("%9s", string); // ask not more than 9 characters
remember that you need one more byte for '\0' (null terminator).

the problem is you are taking "end of string" as the last input in for loop.you do not need the variable "l". you can do some think like that
int main()
{
char new_string[100];
char string1[100];
scanf("%s",string1);
printf("original_number = %s\n",string1);
int i;
for(i = 0; i<=strlen(string1); i++){
new_string[i] = string1[i-1];
printf("%c\n",new_string[i]);
}
printf("rev_number = %s\n",new_string);
}

Related

C - Reverse order of words in an array of Strings

I did this program to reverse the order of the words in the give string. (And it works)
i.e. Output: sentence first the is This
However I am stuck when it comes to adding another sentence to the array.
For example I need to have an array {"This is the first sentence", "And this is the second"} producing as output: sentence first the is This , second the is this And
int main() {
char str[] = {"This is the first sentence"};
int length = strlen(str);
// Traverse string from end
int i;
for (i = length - 1; i >= 0; i--) {
if (str[i] == ' ') {
// putting the NULL character at the position of space characters for
next iteration.
str[i] = '\0';
// Start from next character
printf("%s ", &(str[i]) + 1);
}
}
// printing the last word
printf("%s", str);
return 0;
}
I am new to C so its not surprising that I got stuck even if the solution is quite easy. Any help would be appreciated! Thanks!
Since you already have the code to print the words of one string in reverse order, I would suggest making that a function which takes a single string as an argument, i.e.:
void print_words_reverse(char * const str) {
// your current code here
}
Then you can call it separately for each string:
char strings[][30] = {
"This is the first sentence",
"And this is the second"
};
for (int i = 0; i < sizeof(strings) / sizeof(*strings); ++i) {
print_words_reverse(strings[i]);
}
Note that since you are modifying the string (by replacing spaces with NUL bytes), the argument needs to be modifiable, which means you are not allowed to call it (in standard C) with a pointer to a string literal, which means you can't simply use const char *strings[] = { "first", "second" }. You could get rid of the ugly constant length (here 30) reserved for every string by making your code not modify the argument string. Or you could have a separate char array for each sentence and then use pointers to those (modifiable) strings.
First, you can try with a two-dimensional array or use an array of pointers.
Secondly, in your approach, you lose the initial value of your string, I don't know how important it is.
This is my fast approach using arrray of pointers.
#include <stdio.h>
#include <string.h>
static void print_word(const char *str)
{
for (int i = 0; str[i] && str[i] != ' '; i++)
printf("%c", str[i]);
putchar(' ');
}
int main(void)
{
int len;
const char *str[] = {"This is the first sentence",
"And this is second", NULL};
for (int i = 0; str[i]; i++) {
for (len = strlen(str[i]); len >= 0; len--) {
if (len == 0)
print_word(&str[i][len]);
else if (str[i][len] == ' ')
print_word(&str[i][len + 1]);
}
putchar('\n');
}
printf("Initial value of array of strings [%s | %s] \n", str[0], str[1]);
return 0;
}
output is:
sentence first the is This
second is this And
Initial value of array of strings [This is the first sentence | And this is second]
I suggest you using memcpy but without altering too much your code this seems to work
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_STRING_LENGTH 100
int main()
{
char *str[] = {"This is the first", "And this is the second sentence"};
const size_t NUM_STRING = sizeof(str)/sizeof(char*);
/*%z used to print size_t variables*/
printf("%zd strings found\n", NUM_STRING);
int length[2];
int i;
for (i=0; i<NUM_STRING; i++)
{
length[i] = strlen(str[i]);
}
printf("length initialized %d %d\n", length[0], length[1]);
// Traverse string from end
int j = 0;
char temp[MAX_STRING_LENGTH];
printf("\n\n");
for (j=0; j<NUM_STRING; j++)
{
/*Make sure the string respect the MAX_STRING_LENGTH limit*/
if (strlen(str[j])>MAX_STRING_LENGTH)
{
printf("ERROR: string %d exceding max string length %d defined in constant "
"MAX_STRING_LENGTH. Exiting from program.\n", j, MAX_STRING_LENGTH);
exit(1);
}
//reset temporary string
memset(temp, '\0', sizeof(temp));
//printf("temp variable reinitialized\n");
for (i = length[j] - 1; i >= 0; i--)
{
temp[i] = str[j][i];
if (str[j][i] == ' ')
{
// putting the NULL character at the position of space characters for next iteration.
temp[i] = '\0';
// Start from next character
printf("%s ", &(temp[i]) + 1);
}
}
// printing the last word
printf("%s ", temp);
}
printf("\n");
return 0;
}

removing duplicated chars from string in C

My program has to look for duplicated chars (that comes one after another) and remove them. So my program does work, but in case I put "PLLNSIS", I get "PLNSISS". I overwrite the char that I find out is duplicated, but in the end, i recieve a copy of the last char.
void main()
{
int length;
char *myString;
printf("Enter the length of the string \n");
scanf("%d", &length);
myString = (char*)malloc((length+1) * sizeof(char));
assert(myString);
printf("Now enter the string: (max %d letters) \n", length);
fseek(stdin, 0, SEEK_END); //flushing the buffer
fgets(myString, length+1, stdin); //calling the input function
no_Straight_Letters(myString);
free(myString);
}
void no_Straight_Letters(char *myString)
{
int i, j = 0, length = strlen(myString);
for (i = 1; i < length-1; i++)
{
if (myString[j] == myString[i])
{
myString[j] = myString[i];
myString[i] = '\0';
}
else myString[++j] = myString[i];
}
myString[length] = '\0'; //last char of the string
printf("And the new string is.... --> ");
puts(myString);
}
I found out the cause but when I fix it, I get nothing on the screen.
The problem is
myString[length] = '\0';
It will be
myString[++j] = '\0';
This works because at the end of the looping j points to the last valid character. Then if you increase it and put \0 there - it will make the string.
You can emulate the behavior of having \n with this small addition (which is not likely to be needed).
myString[++j]='\n';
myString[++j]=0;
Also as a small modification you can remove the redundant assignment in your code. it's unnecessary.
if (myString[j] == myString[i])
{
myString[i] = '\0';
}
There are two issues:
First, you miss the last character; you might not have noticed it, because the last character of your fgets-input is probably a newline which you do not see. So you'd iterate like for (i = 1; i <= length-1; i++).
Second, you cut off the string at length, which is larger then the final string; use myString[j+1] = '\0' instead.
Minor issue: The code in your if is useless, you can omit it.
void no_Straight_Letters(char *myString)
{
int i, j = 0, length = strlen(myString);
for (i = 1; i <= length-1; i++)
{
if (myString[j] != myString[i])
myString[++j] = myString[i];
}
myString[j+1] = '\0'; //last char of the string
printf("And the new string is.... --> '%s'",myString);
}
int main()
{
char myString[] = "PLLNSISSSHERBERTTTA";
no_Straight_Letters(myString);
}

Beginner C, why is a bunch of random stuff added to my string?

I have the following program that I want to read in my name (Sahand) character by character and store in a string:
#include <stdio.h>
int main(int argc, const char * argv[]) {
char temp;
char str[6];
int i;
for ( i = 0 ; i < 6 ; i++ )
{
scanf(" %c",&temp);
printf("Our temp is: %c\n",temp);
str[i] = temp;
printf("Our total string is: %s\n",str);
}
printf("Program ended with the string: %s\n",str);
return 0;
}
The output is this:
s
Our temp is: s
Our total string is: s
a
Our temp is: a
Our total string is: sa
h
Our temp is: h
Our total string is: sah
a
Our temp is: a
Our total string is: saha
n
Our temp is: n
Our total string is: sahan
d
Our temp is: d
Our total string is: sahandd\350\367\277_\377
Program ended with the string: sahandd\350\367\277_\377
Program ended with exit code: 0
As you can see, everything is going fine until the final letter, d, is entered, when another d and a bunch of random stuff is added onto the string. Could someone explain to me what is happening here?
You should be adding the null character to the string before printing. Since you're printing inside a loop, add it to the next character. Just absolutely be sure that the for loop doesn't go beyond the bounds of the array.
#include <stdio.h>
int main(int argc, const char * argv[]) {
char temp;
char str[7];
int i;
for ( i = 0 ; i < 6 ; i++ )
{
scanf(" %c",&temp);
printf("Our temp is: %c\n",temp);
str[i] = temp;
str[i+1] = '\0';
printf("Our total string is: %s\n",str);
}
printf("Program ended with the string: %s\n",str);
return 0;
}
Another option is to actually initialize each character in the C-String to be the '\0' character (without ever overwriting the last one); As some others have mentioned in the comments, this can be accomplished in the declaration of the array as such:
char str[7] = { 0 };
You need null character('\0') to end your string(array) at the 5th index in order to tell the compiler that this is the end of string(in your case character array i.e., str). But you were using 5th index to store character 'd'.
The compiler is taking garbage value from the memory
In order to run your program correctly, you need to declare the str array as below:
char str[7];
And insert null character('\0') at (i+1)th position.Look below:
#include <stdio.h>
int main(int argc, const char * argv[]) {
char temp;
char str[7];
int i;
for ( i = 0 ; i < 6 ; i++ )
{
scanf(" %c",&temp);
printf("Our temp is: %c\n",temp);
str[i] = temp;
str[i+1] = '\0';
printf("Our total string is: %s\n",str);
}
printf("Program ended with the string: %s\n",str);
return 0;
}
After reading the comments, I changed the following line in my program:
char str[6];
to
char str[7];
That did the trick and the program executes as I wish.
EDIT:
In addition to changing this line, I added a str[6] = 0; after the variable declaration.

Concatenation of two strings with discarding overlap

I need to build a function in C, that receives two strings str1 and str2 and returns a string that is the concatenation str1 and str2, but I need to discard the last elements of str1 that are equal to the first elements of str2.
Example 1:
str1 = ccabcc
str2 = ccbabd
result : ccabccbabd
Example 2:
str1 = abbcbf
str2 = ab
Result : abbcbfab
Sometimes there is no overlapping.
This problem is trivial imho. Personally, I would go with something like this(it is pseudo code):
function(str1,str2)
int j = 0
int lstr1 = lenght of str 1
int lstr2 = lenght of str 2
while(true)
if(str1[lstr1 - j] == str2[j])
j++
else
break
return str1 + str2[j to end of string]
If I did not make logic mistake, you code should look like something that compare the end of str 1 to beginning of str 2 and increment. Also, my pseudo code don't take into account the string lenght and potential overflow error.
I hope this is what you need:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char *concate(char *first, char *second){
size_t len1 = strlen(first);
size_t len2 = strlen(second);
char *res = (char *)malloc(len1 +len2 +1);
if(res==NULL){
exit(1);
}
if(first[len1-1] == second[0]){
first[len1-1] = 0;
second++;
}
strcpy(res,first);
strcat(res,second);
return res;
}
int main(void){
int i = 0,len = 0;
char arr[] = "ccabcc";
char arr2[] = "ccbabd";
char *res = concate(arr,arr2);
while(res[len] != '\0'){
len++;
}
for(i=0;i<len;i++){
printf("%c",res[i]);
}
printf("\n");
free(res);
return 0;
}
Output:
ccabccbabd
int main(){
char a[256], b[256];
printf("Enter 1st string\n");
gets(a);
printf("Enter the 2nd string\n");
gets(b);
strcat(a,b);
printf("String concatenation is %s\n",a);
}

Pointer error when trying to use "strcpy" in C to copy char elements from one array to another

What I am trying to do is check if the word entered by the user has first five alphabetical letters and if it has, I need to copy those letters to another array.But it gives me an error saying "passing argument 1 of strcpy makes pointer from integer without cast[enabled by default]".
char s1[100];
char a1[100];
char alpha[5]={'a','b','c','d','e'};
int i,j,k=0;
printf("Enter a word");
fgets(s1,100,stdin);
for(i=0;i<strlen(s1);i++)
{
for(j=0;j<5;j++)
{
if(s1[i]==alpha[j])
{
strcpy(a1[k],s1[i]);
k++;
}
}
}
Need help to figure out what is wrong with this
strcpy has two input parameters char *. You can't use it for two characters. If you want to copy one character from one array to another then you need to use = operator as a1[k] = s1[i]
You only need one loop:
Replace char by char:
for(i = 0; i < strlen(s1); i++)
{
a1[i] = s1[i];
}
Or, use strcpy like this: strcpy(a1, s1);
Answering your comment:
I tried a1[k]= s1[i] but it displays some vague characters for a1 ex-: if s1 is "abc" , a1 displays as "abc!"
C strings need to be null terminated.
Try doing this:
char s1[100] = {0};
char a1[100] = {0};
Small example:
#include <string.h>
#include <stdio.h>
int main()
{
char s1[100] = {0};
char a1[100] = {0};
int i,j,k=0;
printf("Enter a word: ");
fgets(s1,100,stdin);
for(i = 0; i < strlen(s1); i++)
{
a1[i] = s1[i];
}
printf("a1 now contains: %s", a1);
return 0;
}

Resources