On-line: гостей 0. Всего: 0 [подробнее..]
Программисты всех стран, объединяйтесь!

АвторСообщение



ссылка на сообщение  Отправлено: 06.07.17 20:24. Заголовок: How to read a string from the user and concatenate it with a constant string and print it in C?


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.

Спасибо: 0 
ПрофильЦитата Ответить
Ответов - 2 [только новые]





ссылка на сообщение  Отправлено: 06.07.17 20:34. Заголовок: There are several ap..


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

 
#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;
}


The program output might look like

 
Enter a sentence: is a good day.
The sentence is: Today is a good day.


Take into account that the function fgets includes the new line character in the array. This statement

 
s[ strcspn( s, "\n") ] = '\0';


removes it.


Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 07.07.17 18:54. Заголовок: ok thanks for help :..


ok thanks for help :)

Спасибо: 0 
ПрофильЦитата Ответить
Ответ:
1 2 3 4 5 6 7 8 9
большой шрифт малый шрифт надстрочный подстрочный заголовок большой заголовок видео с youtube.com картинка из интернета картинка с компьютера ссылка файл с компьютера русская клавиатура транслитератор  цитата  кавычки моноширинный шрифт моноширинный шрифт горизонтальная линия отступ точка LI бегущая строка оффтопик свернутый текст

показывать это сообщение только модераторам
не делать ссылки активными
Имя, пароль:      зарегистрироваться    
Тему читают:
- участник сейчас на форуме
- участник вне форума
Все даты в формате GMT  3 час. Хитов сегодня: 3
Права: смайлы да, картинки да, шрифты да, голосования нет
аватары да, автозамена ссылок вкл, премодерация откл, правка нет