After i put a name in the terminal and it is shorter, then 20 chars, it wants inputs until i have filled all the 20 positions in the array.
I know it is because of the for cycle i have there, but I don't know how else to fill that end of the array with nothing("").
In the array there is for example this "Helloworld\n123\n123"
Thank you for help in advance.
#define NAME 20
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
main(void) {
char name[NAME] = {""};
malloc(sizeof(name[NAME]));
printf("Choose your name: ");
for (int i = 0; i < NAME; i++) {
scanf("%c", &name[i]);
}
//Welcome and the name
printf("Welcome: ");
for (int i = 0; i < NAME; i++) {
printf("%c", name[i]);
}
return 0;
}
You need to stop reading at a newline (+should also check return codes).
A loop like:
size_t i=0;
for (; i < sizeof(name)-1; i++) {
if (1==(scanf("%c",&name[i]))){ if (name[i]=='\n') break; }
else if (feof(stdin)) break; //end of file?
else return perror("getchar"),1; //report error
}
name[i]='\0';
will achieve that (can also use getchar/getc/fgetc instead of scanf)
or you can use fgets:
if(NULL==fgets(name,sizeof(name),stdin)) return perror("fgets"),1;
//erase a possibly included newline at the end
//(won't be there if you pressed Ctrl+D twice rather than
//Enter to submit your input or if you're at the end of
//a stdin redirected from a file)
size_t len = strlen(name);
if(name[len-1]=='\n') name[len-1]='\0';
Whole program with both versions (in the if(0){...}else{...}) :
#define NAME 20
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
int main(void) {
char name[NAME] = {""};
//malloc(sizeof(name[NAME])); //a useless memory leak; don't do this!
printf("Choose your name: ");
if(0){
if(NULL==fgets(name,sizeof(name),stdin)) return perror("fgets"),1;
size_t len = strlen(name);
if(name[len-1]=='\n') name[len-1]='\0';
}else{
size_t i=0;
for (; i < sizeof(name)-1; i++) {
if (1==(scanf("%c",&name[i]))){ if (name[i]=='\n') break; }
else if (feof(stdin)) break; //end of file?
else return perror("getchar"),1;
}
name[i]='\0';
}
//Welcome and the name
printf("Welcome: ");
for (int i = 0; i < NAME; i++) {
printf("%c", name[i]);
}
return 0;
}
If you have to use scanf and %c format:
char *readLineUsingCharAndScanf(char *buff, size_t size, FILE *fi)
{
char ch;
char *wrk = buff;
while(size-- && fscanf(fi, "%c", &ch) == 1 && ch != '\n' ) *wrk++ = ch;
*wrk = 0;
return buff;
}
void dumpString(const char *restrict str, size_t size)
{
while(*str && size--)
{
printf("%03d [0x%02x] - %s\n", *str, *str, (*str >= 32 & *str <= 127) ? (char[]){'\'', *str, '\'', 0} : "not printable");
str++;
}
}
int main(void)
{
char name[20];
dumpString(readLineUsingCharAndScanf(name, 19, stdin), 20);
}
https://godbolt.org/z/vWvP68TbW
scanf() is not the best tool for your purpose. Here is a simple and safe solution:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define NAME 20
int main(void) {
char name[NAME];
int c;
size_t i;
printf("Enter your name: ");
i = 0;
while ((c = getchar()) != EOF && c != '\n') {
if (i < sizeof(name) - 1)
name[i++] = c;
}
name[i] = '\0';
//Welcome and the name
printf("Welcome: %s\n", name);
return 0;
}
If you must use scanf(), use this:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define NAME 20
int main(void) {
char name[NAME];
char c;
size_t i;
printf("Enter your name: ");
i = 0;
while (scanf("%c", &c) == 1 && c != '\n') {
if (i < sizeof(name) - 1)
name[i++] = c;
}
name[i] = '\0';
//Welcome and the name
printf("Welcome: %s\n", name);
return 0;
}
Thank you everyone for answering. Unfortunately the first two answers are too complicated for me yet. And the third one was not working properly.
But I found the simplest answer. :) Many thanks
#include <stdio.h>
int main(void)
{
char name[20];
printf("Choose your name: ");
scanf("%[^\n]*c",name);
printf("My name is %s",name);
}
For your needs I would use scanf with the string conversion specifier %s. In this case, the input name would be read and stored character by character in the buffer until the whitespace would be read. Here is the code.
#define NAME 20
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char name[NAME] = {""};
malloc(sizeof(name[NAME]));
printf("Choose your name: ");
scanf("%s", &name);
printf("%s", &name);
return 0;
}
Related
here is code and i need help to find the place of letter.The strcmp is not working and i dont now where is the proble to fix.
#include <string.h>
int main(void)
{
char s[30]="fiordi";
char *c;
int cp,i,place;
printf("Enter char: ");
scanf("%s",&c);
for(i=0; i<6; i++){
cp=strcmp(s[i],c);
if( cp == 0 ){
place=i;
}
}
printf("the place is :%d",place);
}
#include <string.h>
#include <stdio.h>
int main(void)
{
char s[30]="fiordi";
size_t s_len = strlen(s);
int place, c;
printf("Enter char: ");
scanf("%c",&c);
for(place = 0; place < s_len; place++)
if(s[place] == (char)c)
break;
if(place == s_len)
printf("\nchar not found in string\n");
else
printf("the place of char in \"%s\" is in position %d", s, place);
}
strcmp compares strings, not characters. Without going into the details of why it doesn't work, you could just compare the characters directly:
if(s[i] == c[0] ){
place=i;
}
This question already has answers here:
Difference between scanf("%c", &c) and scanf(" %c", &c) [duplicate]
(3 answers)
Reading a character with scanf_s
(3 answers)
Closed 4 years ago.
In the main function if i simply declare the replacement character like this..
c = '*';
the program will keep looping normal and work normal after user enters y or Y to proceed.
But if i want the user to enter the replacement character and do this..
c = getchar();
after the user enters either y or Y, the loop ends and the program just closes.
Why is this?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define BUFF_SIZE 512
void getRandomStr(char s1[]);
void strreplace(char s1[], char chrs[], char c);
void check(char s2[], char chrs[]);
char cont(void);
int main()
{
char s1[BUFF_SIZE];
char s2[BUFF_SIZE], c;
char proceed = 0;
do {
getRandomStr(s1);
printf("Your random string is: %s\n", s1);
/* gets(s1) */
printf("\nPlease enter up to 20 letters to be replaced: ");
gets(s2);
printf("\nPlease enter a replacement character (Ex. *, $, etc.): ");
c = getchar();
check(s1, s2);
printf("\nModified string after replacement is: ");
strreplace(s1, s2, c);
proceed = cont();
} while (proceed == 'Y' || proceed == 'y');
}
void getRandomStr(char s1[]) {
int i;
srand(time(NULL));
for (i = 0; i < 41; i++) {
char c = rand() % 26 + 'A';
s1[i] = c;
}
s1[41] = '\0';
}
void strreplace(char s1[], char chrs[], char c)
{
int i = 0;
while (chrs[i] != '\0') {
for (int j = 0; s1[j] != '\0'; j++) {
if (s1[j] == chrs[i])
{
s1[j] = c;
}
}
i++;
}
puts(s1);
}
char cont()
{
char proceed;
printf("\nWould you like to run the program again (y/n)? ");
scanf_s("%c%*c", &proceed);
return proceed;
}
void check(char s2[], char chrs[])
{
int i = 0;
while (chrs[i] != '\0') {
for (int j = 0; s2[j] != '\0'; j++) {
if (!(chrs[i] >= 'A' && chrs[i] <= 'Z'))
{
printf("An invalid character was entered.\n");
break;
}
}
i++;
}
}
This is what I theorized it should be but it seemed like it doesn't work.
HELP PLEAZEE
int main()
{
char input[50];
int i;
do{
printf("ENTER A CHARACTER:");
scanf("%s",&input);
if(isalpha(input)!=0){
printf("YOU INPUTTED A CHARACTER");
i++;
}else{
printf("INVALID INPUT\n");
}
}while(i!=1);
}
isalpha takes an integer as an argument.
You are giving a char array.
You should loop for the number of characters given in input[], if you want more than one character (hard to tell from this code).
This exits if you give exactly one character but keeps going if you give more than one:
#include <stdio.h>
#include <string.h>
int main()
{
char input[50];
int i = 0, j;
size_t len = 0;
do
{
printf("ENTER A CHARACTER:");
scanf("%s",&input);
len = strlen(input);
for(j = 0; j < len; j++) {
if(isalpha(input[j]))
{
i++;
printf("YOU INPUTTED A CHARACTER %d\n", i);
}
else
{
printf("INVALID INPUT\n");
break;
}
}
} while(i!=1);
}
I am trying to input string into fixed size char array.
I have a questions:
when I input a string which is bigger than the char array, the array become bigger without any additional declaration. I want to make the code only take the string that 'equal or smaller than the char array'.
Thank You.
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
/***************************Function****************************/
int string_length(char s[]) {
int c = 0;
while (s[c] != '\0')
c++;
return c;
}
/**************************************************************/
char *str;
int arrSize;
void opt1()
{
printf("Enter array size: ");
scanf("%d", &arrSize);
arrSize=arrSize+1;
str = malloc(arrSize);
return;
}
void opt2()
{
printf("Enter characters: ");
scanf("%s", str);
length = string_length(str);
printf("your input is '%s'\n", str);
printf("your input length is '%d'\n", length);
return;
}
int main()
{
int input = 0;
while(input != 3) {
printf("\n NAME \n");
printf("\n");
printf("--------------------------------------\n");
printf("1) Making Array \n");
printf("2) Check Array \n");
printf("3) Quit\n");
printf("\nEnter selection: ");
scanf("%d", &input);
if( input == 1 ) {
/* */
opt1();
}
else if(input == 2) {
opt2();
}
}
return 1;
}
OP wants to read data, yet if larger that the target array, then do not change the target array.
// 1: success
// -1 EOF
// 0: Input too long
int read_array(char *buffer, size_t size) {
char tmp[size];
size_t i = 0;
int ch;
while ((ch = fgetc(stdin)) != EOF && ch != '\n') {
if (i < size) {
tmp[i++] = ch;
}
}
if (ch == EOF && i == 0) return EOF;
if (i >= size) return 0; // too many
memcpy(buffer, tmp, i);
buffer[i] = '\0';
return 1;
}
Normally code could use fgets(), but there are corner cases that fail to meet OP goals.
To read in a whole line, you can use fgets:
char line[80];
if (fgets(line, sizeof line, stdin) != NULL) {
// use the input
}
Now you won't need to check if the user entered more than the limit, since fgets will only get the first 79 (-1 for null terminator) characters; the remainder, if any, will be ignored.
I am trying to create a program that can modify a text according to the user key. It seems to work well, until I input something and it adds extra things.
For example, if I add the word hello and a key of 3, it says khoor plus some extra weird characters. Can you tell me please what is the problem? Thank you very much.
#include <stdio.h>
#include <ctype.h>
#define MAXSIZE 100
void encrypt(senTence[], int key);
int main(void)
{
int userKey;
char sentence[MAXSIZE];
printf("Input the text that you want to encrypt:\n> ");
fgets(sentence, 99, stdin);
// printf("\nThe string that you wrote is:\n%s\n\n", sentence);
printf("Input the key:\n");
scanf("%d", &userKey);
//printf("\nThe key that you selected is: %d\n\n", userKey);
encrypt(sentence, userKey);
return 0;
}
void encrypt(const char senTence[], int key)
{
int i = 0;
char q[MAXSIZE];
for(i = 0; senTence[i] != '\0'; ++i)
{
if( ( isupper(senTence[i]) ) || ( islower(senTence[i]) ) )
{
q[i] = senTence[i] + (char)key;
}
else
{
q[i] = (senTence[i]);
}
}
printf("%s", q);
}
You didn't terminate the result string q in encrypt().
Add the following line before printf().
q[i] = '\0';
Another way is initialize q to all-zero:
char q[MAXSIZE] = {0};
You forgot to null terminate your array q, so using as a string will not be possible.
After you have performed the required operation on all the elements of the senTence and stored it to q, you need to null terminate q.
Use
q[i] = '\0';
printf("%s\n", q);
I ran the code, was giving a few warnings and an error, related to the function prototype. I fixed that and it is working fine now!
#include <stdio.h>
#include <ctype.h>
#define MAXSIZE 100
void encrypt(const char senTence[], int key);
int main(void)
{
int userKey;
char sentence[MAXSIZE];
printf("Input the text that you want to encrypt:\n> ");
fgets(sentence, 99, stdin);
// printf("\nThe string that you wrote is:\n%s\n\n", sentence);
printf("Input the key:\n");
scanf("%d", &userKey);
//printf("\nThe key that you selected is: %d\n\n", userKey);
encrypt(sentence, userKey);
return 0;
}
void encrypt(const char senTence[], int key)
{
int i = 0;
char q[MAXSIZE];
for(i = 0; senTence[i] != '\0'; ++i)
{
if( ( isupper(senTence[i]) ) || ( islower(senTence[i]) ) )
{
q[i] = senTence[i] + (char)key;
}
else
{
q[i] = (senTence[i]);
}
}
printf("%s", q);
}