c programming - printing sentences - c

this is my first time using this site as well as learning c programming.
I'm trying to write a code which lets a user type in a sentence and the code prints it back out.
My attempt:
#include<stdio.h>
int main()
{
char array[1000];
printf("Please enter a phrase: ");
int index = 0;
while(array[index]!= '\0')
{
scanf("%c",&array[index]);
++index;
}
index = 0;
while(array[index]!= '\n')
{
printf("%c",array[index]);
++index;
}
}
I can't find the reason to why this code does not work.

You can get expected output using your concept also.. Try something using following code.
#include<stdio.h>
int main()
{
char array[1000];
printf("Please enter a phrase: ");
int index =0;
scanf("%c",&array[index]);
while(array[index]!='\n')
{
scanf("%c",&array[++index]);
}
index=0;
while(array[index]!= '\n')
{
printf("%c",array[index]);
++index;
}
printf("\n");
}

Okay, so first and foremost you'll need to initialize all your array. If you don't, the user input will print along with lots of meaningless garbage.
Secondly, the test portion of your first while loop checks for a null character which will never exist because "array[]" is just a simple character array (not a string) therefore, a call to scanf() doesn't insert the null character at the end. This causes an infinite loop.
Thirdly, your first while loop should be a do-while so that you first read a character, then test the character, otherwise if the "index" variable increments first...
Lastly, I posted the code that i used to get it to run using the method that you chose. However, as an alternative to the method you chose, the c standard library has the gets() function, which will allow you to read an entire line of input and return the string entered (actually it returns a pointer to the character array created but i think you catch my drift), and the puts() function which prints a string pointed to by the pointer used as an argument.
For more info on this problem in general, including gets() and puts(), refer to "C Programming A Modern Approach" by K.N. King, Chapter 13: Strings.I hope this helps.
Happy Coding!! :)
#include <stdio.h>
int main()
{
int index = 0;
char array[1000];
while(index < 1000){
array[index] = '0';
index++;
}
printf("Please enter a phrase: ");
index = 0;
do {
scanf("%c", &array[index]);
} while(array[index] != '\n' && index++ < 1000);
index = 0;
while(index < 1000)
printf("%c", array[index++]);
}

I think your looking for this:
#include<stdio.h>
int main() {
char array[1000];
printf("Please enter a phrase: ");
scanf ("%[^\n]%*c", array);
printf("\n%s", array);
return 0;
}

Related

take user's input and then print the alphabet series

My aim is to take user's input and then print the alphabet series. Printing the alphabet series from the point the user entered the input.
#include<stdio.h>
int main(){
char alpha_U;
printf("Enter the letter from where you want in upper case: ");
scanf("%c",alpha_U);
for(char i = alpha_U; i <= 'Z'; i++){
printf("%c",i);
}
return 0;
}
Your code is almost fine, except for
scanf("%c", alpha_U);
which requires a pointer as second argument.
I am not expert of C or C++ programming, so the thing I would suggest you is to checkout the documentation on cplusplus.com.
Specifically, here is how scanf is documented:
https://cplusplus.com/reference/cstdio/scanf/
The additional arguments should point to already allocated objects of the type specified by their corresponding format specifier within the format string.
so in your case you should be doing
scanf("%c", &alpha_U);
I am also starting out with C so I apologize if I missed any details.
scanf("%c", alpha_U);
is missing & in the front of the variable. Corrected below.
scanf("%c",&alpha_U);
I rewrote the code so I can get the user input in the main function.
#include<stdio.h>
#include <ctype.h>
int main(int argc, char *argv[]){
char lowerCase,upperCase;
printf("Enter one chacters to be capitalized\n");
scanf("%c", &lowerCase);
upperCase = toupper(lowerCase);
printf("%c",upperCase);
return 0;
}
#include<stdio.h>
int main()
{
char alpha_U;
printf("Enter the letter from where you want in upper case: ");
scanf("%c", &alpha_U);//Here,you should add '&' before 'alpha_U'
for (char i = alpha_U; i <= 'Z'; (int)i++) {//Then,add '(int)' before 'i'
printf("%c", i);
}
return 0;
}

How to count the length of each word in a string of characters

I'm a beginner programmer and im trying to solve some exercises and i needed some help with one of them.
The exercise goes like this:
We need to input a string of characters , read it and print out the length of each word.
This is what i did
int main()
{
char str[N+1+1];
int i=0;
int pos=0;
int wordlen=0;
int word[60]={0,};
printf("Please enter the string of characters: ");
gets(str);
while(i<strlen(str))
{
if(!isalpha(str[i]))
{
wordlen=0;
i++;
}
if(isalpha(str[i]))
{
wordlen++;
i++;
pos=i;
}
word[pos]=wordlen;
wordlen=0;;
i++;
}
for(i=0;i<20;i++)
{
if(word[i]==0) // here im just trying to find a way to avoid printing 0's but you can ignore it if you want
{break;}
else
printf("%d ",word[i]);
}
return 0;
}
The problem is that when i try to compile it for example: I input "hi hi hi" its supposed to print 2 2 2 but instead it's printing nothing.
Can i ask for some help?
I failed to follow OP's logic.
Perhaps begin again?
End-of-word
To "count the length of each word", code needs to identify the end of a word and when to print.
Detecting a non-letter and the current word length > 0 indicates the prior character was the end of a word. Note that every C string ends with a non-letter: '\0', so let us iterate on that too to insure loop ends on a final non-letter.
int word_length = 0;
int strlength = strlen(str); // Call strlen() only once
while (i <= strlength) {
if (isalpha(s[i])) {
word_length++;
} else {
if (word_length > 0) {
printf("%d ", word_length);
word_length = 0;
}
}
}
printf("\n");
gets()
gets() is no longer in the C library for 10 years as it is prone to over-run. Do not use it.
we are supposed to use gets. is unfortunate and implies OP’s instruction is out-of-date. Instead, research fgets() and maybe better instruction material.
Advanced
is...() better called as isalpha((unsigned char) s[i]) to handle s[i] < 0.
In general, better to use size_t than int for string sizing and indexing as the length may exceed INT_MAX. That is not likely to happen with OP's testing here.

Using scanf for character input, but the do-while loop wont stop at the null character

I'm completely new to programming (1st term in uni) and I can't keep up with my lecturer. At the moment I'm stuck on this exercise (for much more time than I'm willing to admit). I've tried to find help on the internet (in this site and others as well), but I can't, since our lecturer has us use a very simple form of c. I'm not asking necessarily for a complete answer. I'd really appreaciate even some hints about where I'm on the wrong. I understand that it might be really simple for some, that the question might seem ignorant or stupid and I feel bad for not getting what's wrong, but I need to try to understand.
So, what I'm trying to do is use scanf and a do while loop so the user can input characters in an array. But I don't understand why the loop won't stop when the user presses ENTER. There's more to the code, but I'm trying to take it slowly, step by step. (I'm not allowed to use pointers and getchar etc).
#include <stdio.h>
main()
{
char a[50];
int i;
printf("Give max 50 characters\n");
i=0;
do
{
scanf("%c", &a[i]);
i=i+1;
}
while((i<=50) && (a[i-1]!='\0'));
for(i=0; i<50; i++)
printf("%c", a[i]);
}
There aren't any nul-terminated strings here, but only string arrays.
So, when pressing enter, a[i-1] is \n not \0 (scanf with %c as parameter doesn't nul-terminate the strings, and ENTER is just a non-nul character with code 10 AKA \n)
Then don't print the rest of the string because you'll get junk, just reuse i when printing the string back:
#include <stdio.h>
main()
{
char a[50];
int i;
printf("Give max 50 characters\n");
i=0;
do
{
scanf("%c", &a[i]);
i=i+1;
}
while((i<sizeof(a)) && (a[i-1]!='\n')); // \n not \0
int j;
for(j=0; j<i; j++) // stop at i
printf("%c", a[j]); // output is flushed when \n is printed
}
Also test with i<50 not i<=50 because a[50] is outside the array bounds (I've generalized to sizeof(a))
Here is another way you can do this.
#include <stdio.h>
// define Start
#define ARRAY_SIZE 50
// define End
// Function Prototypes Start
void array_reader(char array[]);
void array_printer(char array[]);
// Function Prototypes End
int main(void) {
char user_input[ARRAY_SIZE];
printf("Please enter some characters (50 max)!\n");
array_reader(user_input);
printf("Here is what you said:\n");
array_printer(user_input);
return 0;
}
// Scans in characters into an array. Stops scanning if
// 50 characters have been scanned in or if it reads a
// new line.
void array_reader(char array[]) {
scanf("%c", &array[0]);
int i = 0;
while (
(array[i] != '\n') &&
(i < ARRAY_SIZE)
) {
i++;
scanf("%c", &array[i]);
}
array[i + 1] = '\0';
}
// Prints out an array of characters until it reaches
// the null terminator
void array_printer(char array[]) {
int i = 0;
while (array[i] != '\0') {
printf("%c", array[i]);
i++;
}
}
You may try with this code:
#include <stdio.h>
main()
{
char a[50];
int i;
printf("Give max 50 characters\n");
i=0;
do {
scanf("%c", &a[i]);
i=i+1;
} while(i<50 && a[i-1] != '\n');
a[i] = 0;
for(i=0; a[i] != 0; i++)
printf("%c", a[i]);
}
The function scanf("%c", pointer) will read one character at a time and place it at the pointer location. You are looking for '\0', which is a valid string terminator, but the newline character you get when you press ENTER and that you should be looking for is '\n'.
Also, it is a good idea to terminate the string you have read by adding a '\0' at the end (really a zero). Then use it to stop printing or you may print the "rest" of the contents of an uninitialized char array.

Substring in C (what will happen to the remaining in array)

I have given a task to generate a sub string for the given input in C. The code as follows.
#include<stdio.h>
int main(){
char a[1000];
char *sub;
int startFrom = 0;
int endAt = 0;
printf("Enter the String: ");
scanf("%s", a);
printf("Start From? ");
scanf("%d", &startFrom);
printf("End At? ");
scanf("%d", &endAt);
sub = &a[startFrom];
a[endAt] = '\0';
printf("%s\n", sub);
return 0;
}
The code however works fine, but what will happen to the rest of the characters in the array?
The rest of the array remains the same; it's just that you changed one of the characters in the array to null('\0'). So if you try to access any other character after (or before) the a[endAt] character, you would be able to do so.
Check it out Your code with some extra at Ideone.com.
However as you can see, when you try to print the original array, it would be printed only till the first '\0' character.

Check whether string is palindrome

I am writing some code to check whether a string is a palindrome, but it's giving me a runtime error. I can't spot where the error is. Please help.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char a[20];
int n,c;
c=0;
printf("enter the size of the string ");
scanf("%d",&n);
printf("enter the string ");
fgets(a,n,stdin);
for(int i=0;i<(n-1)/2;i++)
{
if(a[i]==a[n-1-i])
{
c=0;
}
else
{
c=1;
break;
}
}
if(c==0)
printf("string is palindrome");
else
printf("string is not palindrome");
return 0;
}
Well, the first thing I notice, upon compiling and executing this, is
that it doesn’t let you enter the string. This is due to the way you’re
taking input:
printf("enter the size of the string ");
scanf("%d",&n);
printf("enter the string ");
fgets(a,n,stdin);
It runs scanf("%d",&n);. So the user types, say, 6, followed by the
enter key. Hokay, so scanf looks at those characters 6\n, takes the
6, converts to a number, and n ends up with a value of 6.
But that newline is still there. scanf didn’t do anything with it
because it’s not numeric. So, when the code gets to here:
fgets(a,n,stdin);
It then reads that newline and thinks “Okay! The user entered an empty
string.” (Yes I know I’m being anthropomorphic, sue me.)
This sort of behavior is why I avoid using scanf. I would code it this
way:
fgets(a, sizeof(a), stdin);
n = atoi(a);
printf("enter the string ");
fgets(a, sizeof(a), stdin);
Note that this also limits each fgets to the size of the buffer,
avoiding potential buffer overflows. This is an important consideration
with working code, because a buffer overflow can easily lead to a
vulnerability that can be exploited to break security. Best to develop
good habits even with simple learning programs like this.
Note also that a better way to do this would be to simply read the
string by itself, then compute its length with strlen.
At this point, it seems to be working correctly, so I won’t delve into
the rest of it. However, if you take my advice about computing the
length, there’s one more thing to be aware of. If you add this line
(temporarily, just for debugging purposes):
printf("%d\n", strlen(a));
You will see that you have one more character than you expect. That is
because fgets retains the newline. So, we want to get rid of it:
a[strlen(a) - 1] = '\0';
This isn’t necessary if you use the value of n, because then it will
just ignore the newline and use the n characters preceding it. But it
would be necessary if you’re computing the length.
Take a look at this code, that's how I have implemented it (remember to #include <stdbool.h> or it will not work):
for(i = 0; i < string_length; i++)
{
if(sentence[i] == sentence[string_lenght-1-i])
palindrome = true;
else
{
palindrome = false;
break;
}
}
Doing that it will check if your sentence is palindrome and, at the first occurence this is not true it will break the for loop. You can use something like
if(palindrome)
printf(..);
else
printf(..);
for a simple prompt for the user.
Example :
radar is palindrome
abba is palindrome
abcabc is not palindrome
Please , pay attention to the fact that
Abba
is not recognized as a palindrome due to the fact that ' A ' and 'a' have different ASCII codes :
'A' has the value of 65
'a' has the value of 97
according to the ASCII table. You can find out more here.
You can avoid this issue trasforming all the characters of the string to lower case characters.
You can do this including the <ctype.h> library and calling the function int tolower(int c); like that :
for ( ; *p; ++p) *p = tolower(*p);
or
for(int i = 0; str[i]; i++){
str[i] = tolower(str[i]);
}
Code by Earlz, take a look at this Q&A to look deeper into that.
EDIT : I made a simple program (however it's a sample, it can be further optimised and so on, it's just to give you the idea), see if it can help you
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include <ctype.h>
void LowerCharacters(char *word, int word_lenth);
int main(void){
char *word = (char *) malloc(10);
bool palindrome = false;
if(word == 0)
{
printf("\nERROR : Out of memory.\n\n");
return 1;
}
printf("\nEnter a word to check if it is palindrome or not : ");
scanf("%s", word);
int word_length = strlen(word);
LowerCharacters(word,word_length);
for(int i = 0; i < word_length; i++)
{
if(word[i] == word[word_length-1-i])
palindrome = true;
else
{
palindrome = false;
break;
}
}
palindrome ? printf("\nThe word %s is palindrome.\n\n", word) : printf("\nThe word %s is not palindrome.\n\n", word);
free(word);
return 0;
}
void LowerCharacters(char *word, int word_length){
for(int i = 0; i < word_length; i++)
word[i] = tolower(word[i]);
}
Input :
Enter a word to check if it is palindrome or not : RadaR
Output :
The word radar is palindrome.

Resources