Форум » C/C++ для начинающих (C/C++ for beginners) » How to read a string from the user and concatenate it with a constant string and print it in C? » Ответить

How to read a string from the user and concatenate it with a constant string and print it in C?

proneon267: I want to make a program which reads a sentence entered by the user and combines it with word already declared. For example: Enter a sentence : is a good day. The sentence is : Today is a good day. Here "Today" is the constant string while "is a good day" is the input entered by the user.

Ответов - 2

Сыроежка: There are several approaches to do the task. I think that the simplest one is to reserve memory for the prefix "Today" in a character array and then after reading a string to copy this prefix in the beginning of the character array. Here is a demonstrative program that uses this approach [pre2] #include <stdio.h> #include <string.h> #define N 100 int main(void) { char s[N]; char *prefix = "Today "; const size_t PREFIX_LEN = strlen( prefix ); printf( "Enter a sentence: " ); fgets( s + PREFIX_LEN, N - PREFIX_LEN, stdin ); memcpy( s, prefix, PREFIX_LEN ); s[ strcspn( s, "\n") ] = '\0'; printf( "The sentence is: %s\n", s ); return 0; }[/pre2] The program output might look like [pre2] Enter a sentence: is a good day. The sentence is: Today is a good day. [/pre2] Take into account that the function fgets includes the new line character in the array. This statement [pre2] s[ strcspn( s, "\n") ] = '\0'; [/pre2] removes it.

proneon267: ok thanks for help :)



полная версия страницы