why following code is giving garbage value ?
here I am trying to get an string as an input from user character by character. In the following code i have got input from user and stored in string[] array then in order to do some other operations i have stored the same in other array called temp_string[i]. But surprisingly i am getting garbage value in output.and also length calculated using strlen is not correct. can anybody look at this code and explain whats going wrong?
#include<stdio.h>
#include<stdio.h>
int main()
{
char ch;
int i = 0, j = 0;
int length = 0;
int lengthsb = 0;
char string[100];
printf(" Enter the string to divide\n ");
while(ch != '\n')
{
ch = getchar();
string[i] = ch;
i++;
}
char temp_string[i];
printf("%s", string);
i = 0;
while(string[i] != '\n')
{
temp_string[i] = string[i];
i++;
}
length = strlen(temp_string);
printf("Entered string is %s and its length is %d\n", temp_string, length);
}
You forgot to add the null at the end of the string.
C strings are null-terminated, that means that all operations in c strings expect a null to mark the end of the string, including functions like strlen.
you can achieve that just adding:
string[i] = '\0';
After fill the string.
Another thing, what happens if the user enters a string bigger than 100? Is good to validate the input for these cases, otherwise you can get a buffer overflow.
You need to add a NULL - terminated at the end of your string. Add \0.
You need to put a '\0' char at the end of the string so strlen(), printf() and other C functions dealing with strings will work. That is how the C API knows it reached the end of the string.
Also, you don't want to set new characters at the memory space past the string array. So you better check that in your loop (and save a last array item to set the '\0').
while (ch != '\n' && i < 99)
{
ch = getchar();
string[i] = ch;
i++;
}
string[i] = '\0'; // set the string terminator past the end of the input
Remember to do the same after copying the characters to temp_string. (By the way, you can replace that loop with a call to strcpy(), that does exactly that, except it will end only when it finds a '\0'.)
You might also want to read What's the rationale for null terminated strings?
Here is your Final Code:
#include<stdio.h>
#include<stdio.h>
#include<string.h>
int main()
{
char ch;
int i = 0, j = 0;
int length = 0;
int lengthsb = 0;
char string[100];
char temp_string[100];
printf(" Enter the string to divide\n ");
while(ch != '\n')
{
ch = getchar();
string[i] = ch;
i++;
}
string[i]=NULL;
printf("%s", string);
i = 0;
while(string[i] != '\0')
{
temp_string[i] = string[i];
i++;
}
temp_string[i]=NULL;
length = strlen(temp_string);
printf("Entered string is %s and its length is %d\n", temp_string, length);
}
In the above code what exactly you are missing is NULL or '\0' termination of the string. I just added it to make it useful.
Related
When I print 8 or more characters, symbols always print after the 8th character. Does anyone know what is wrong with the code and how can I fix this?
I've tried with different numbers of characters and it always happens when is more than 8 or 8.
#include <stdio.h>
int main() {
char ch = 0;
char temp[100];
int i = 0;
while (scanf("%c", &ch) == 1) {
if (ch != '\n') {
temp[i] = ch;
printf("%s", temp);
i++;
}
}
return 0;
}
My expected result is
1 12 123 123412345123456123456712345678
My actual output is
1 12 123 123412345123456123456712345678xxx
the x represent the symbols
The reason you get funny characters in the output is the temp array is not a proper C string because it is uninitialized so there is not necessarily a null byte '\0' after the ith entry set with temp[i] = ch;.
There are different ways to fix this problem:
you can initialize temp this way: char temp[100] = { 0 };
you can set the byte at temp[i+1] to '\0' in the loop.
Note also that the expected output is not 1 12 123 123412345123456123456712345678, but 112123123412345123456123456712345678 because you do not output a separator between the strings. It would be less confusing to output the strings on separate lines.
Finally scanf() will not return until the user has typed a newline because of buffering performed by the terminal driver and the standard input stream.
Here is a modified version:
#include <stdio.h>
int main() {
char ch;
char temp[100];
size_t i = 0;
while (scanf("%c", &ch) == 1 && i + 2 < sizeof(temp)) {
if (ch != '\n') {
temp[i] = ch;
temp[i + 1] = '\0';
printf("%s", temp);
i++;
}
}
return 0;
}
#chqrlie well explained and offered 2 alternatives.
3rd alternative: change format
printf("%s\n", temp) expects temp to be a string. In C, a string has a null character, else it is not a string.
Code failed to ensure a '\0' in temp[]. The result is undefined behavior (UB).
Code could use a precision to limit the number of characters printed with "%s".
// printf("%s", temp);
printf("%.*s", (int)i, temp);
"%.*s", (int)i, temp will print up to i characters or up to '\0' - which ever comes first. i is cast as (int) because printf expects an int for the precision given as an extra argument as specified by the .* before the s.
int main(void) {
char temp[100];
size_t i = 0;
while (i < sizeof temp && scanf("%c", &temp[i]) == 1 && temp[i] != '\n') {
i++;
}
printf("<%.*s>\n", (int)i, temp);
return 0;
}
I'm trying to create a program that checks if a given array/string is a palindrome or not and its not working. The program just prints "0" on every given array, even on palindromes.
int main()
{
char string[100]= {0};
char stringReverse[100]= {0};
int temp = 0;
int firstLetter = 0;
int lastLetter = 0;
printf("Please enter a word or a sentence: ");
fgets(string, 100, stdin);
strcpy(stringReverse , string); // This function copies the scanned array to a new array called "stringReverse"
firstLetter = 0;
lastLetter = strlen(string) - 1; //because in array, the last cell is NULL
// This while reverses the array and insert it to a new array called "stringReverse"
while(firstLetter < lastLetter)
{
temp = stringReverse[firstLetter];
stringReverse[firstLetter] = stringReverse[lastLetter];
stringReverse[lastLetter] = temp;
firstLetter++;
lastLetter--;
}
printf("%s %s", stringReverse, string);
if ( strcmp(stringReverse , string) == 0)
{
printf("1");
}
else
{
printf("0");
}
}
Lets say we implement a simple fun to do that
int check_palindrome (const char *s) {
int i,j;
for (i=0,j=strlen(s)-1 ; i<j ; ++i, --j) {
if (s[i] != s[j]) return 0; // Not palindrome
}
return 1; //Palindrome
}
I think this is far more simpler ;)
For the code posted in question:
Be aware of fgets(). It stops in the first '\n' or EOF and keeps the '\n' character.
So if you give radar for ex, the result string will be "radar\n", which doesn't match with "\nradar"
The Problem:
Let's say you enter the string RACECAR as input for your program and press enter, this puts a newline character or a '\n' in your buffer stream and this is also read as part of your string by fgets, and so your program effectively ends up checking if RACECAR\n is a palindrome, which it is not.
The Solution:
After you initialize lastLetter to strlen(string) - 1 check if the last character in your string (or the character at the lastLetter index is the newline character (\n) and if so, decrease lastLetter by one so that your program checks if the rest of your string (RACECAR) is a palindrome.
lastLetter = strlen(string) - 1; //because in array, the last cell is NULL
// Add these 2 lines to your code
// Checks if the last character of the string read by fgets is newline
if (string[lastLetter] == '\n')
lastLetter--;
fgets adds a '\n' at the end.
So if the user entered "aba", string contains "aba\n".
reverseString contains "\naba".
So it doesn't match.
After the fgets, add this code
int l = strlen(string) - 1;
string[l] = 0;
This will strip out the '\n' at the end before copying it to reverseString.
That aside, you can do this whole program inplace without the need of a second buffer or strcpy or strlen calls.
You have several issues in your code:
first you forgot the last closing brace };
then you forgot to remove the trailing \n (or maybe also \r under Windows) in string;
you don't need to revert the string into a new string; a one-pass check is enough:
Here is a working code:
#include <stdio.h>
#include <string.h>
int main()
{
char string[100]= {0};
int temp = 0;
int firstLetter = 0;
int lastLetter = 0;
printf("Please enter a word or a sentence: ");
fgets(string, 100, stdin);
firstLetter = 0;
lastLetter = strlen(string) - 1; //because in array, the last cell is NULL
while ((string[lastLetter]=='\n')||(string[lastLetter]=='\r')) {
lastLetter--;
}
// This while reverses the array and insert it to a new array called "stringReverse"
temp = 1;
while(firstLetter < lastLetter)
{
if (string[firstLetter] != string[lastLetter]) {
temp = 0;
break;
}
firstLetter++;
lastLetter--;
}
if ( temp )
{
printf("1");
}
else
{
printf("0");
}
}
You can do it by this simpleway also.
#include <stdio.h>
#include <string.h>
int main()
{
char string[10], revString[10];
printf("Enter string for reversing it...\n");
scanf("%s", string);
int stringLength = strlen(string);
for(int i = 0; string[i] != '\0'; i++, stringLength--)
{
revString[i] = string[stringLength - 1];
}
if(strcmp(string, revString) == 0)
printf("Given string is pelindrom\n");
else
printf("Given string is not pelindrom\n");
}
#include<stdio.h>
#include<string.h>`enter code here`
void fun(char *a);
int main ()
{
char p[100];
char *s=p;
printf("enter the string");
scanf("%[^\n]",s);
fun(s);
}
void fun(char *a)
{
if(*a && *a!='\n')
{
fun(a+1);
putchar(*a);
}
}
// use this approach better time complexity and easier work hope this helps
**i am trying to reverse a string so what i am trying is to take the string to its last position and from there i am storing it to a new character array and printing that but not getting desired output **
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char c[10];
printf("Enter the string:\n");
gets(c);
rev(c);
return 0;
}
void rev(char c[])
{
int i = 0,j = 0;
char s[10];
while(c[j] ! = '\0')//reaching to end of string
{
j++;
}
while(s[i] ! = '\0')
{
s[i] = c[j];//copying string c from end into string s from begining
i++;
j--;
}
s[i+1]='\0';
printf("The string after reverse: %s",s);//printing reversed string
}
while(s[i] ! = '\0')
In above line s[i] is uninitialized and hence you are invoking undefined behaviour by accessing uninitialized value and thus incorrect result.
To fix this, you can rewrite the condition as:
while(j >= 0)
Apart from these, for sane result, you need following two changes:
The final termination should be re-written as:
s[i]='\0';
The initial value of j should be decremented by 1. (As c[j] would point to the null character)
as i is now already pointing past the size of c string.
problem is when you use gets() the buffer is usually dirty. I would suggest you use fflush(stdin) before the gets().
Also the last line where you say s[i+1] = '\0' should be s[i] = '\0' the i already was incremented by one after the last execution of the loop.
And as said above it shouldnt be while (s[i] != '\0')
s is not initialized so God knows whats in there. make it like while ( j >=0) and it should work.
I'm trying to get selected characters from one string into another. Everything looks okay, except the program keeps adding additional characters to the output. And it seems that it tends to add different number of these "unecessary" characters. Where might the problem be?
int main(void) {
int i,j=0;
char string[256];
char second_arr[256];
scanf("%255s", string);
for(i=0;i<256;i++){
if(string[i]=='('||string[i]=='['||string[i]=='{'){
second_arr[j]=string[i];
j++;
}
}
printf("%s", second_arr);
}
Say,
input: (hello)(}[} --->
Output:(([[H
Problem 1: You're not testing scanf for failure. It can return EOF, or zero to indicate the input didn't match your format string.
Problem 2: You're copying all 256 chars even if the user entered fewer, which means you're copying junk.
Problem 3: You're not adding a null terminator to second_arr.
Just do this:
if (scanf("%255s", string) != 1)
{
printf("scanf failed\n");
return 1;
}
for (i = 0; i < 256 && string[i]; i++) {
if(string[i]=='('||string[i]=='['||string[i]=='{'){
second_arr[j]=string[i];
j++;
}
}
second_arr[j] = '\0';
printf("%s", second_arr);
return 0;
Try this:
for (i=0; string[i]!=0; i++) // iterate the input string until the null-character
{
if (string[i] == '(' || string[i] == '[' || string[i] == '{')
second_arr[j++] = string[i];
}
second_arr[j] = 0; // set a null-character at the end of the output string
There is nothing to terminate the second string. Add
||string[i]=='\0'
to your conditions. Also break out of the loop when you see that null char, but only after you have copied it.
You should add at the end of second string second_arr the char '\n' to indicate its end.
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.