While initializing the character array at runtime using for loop statement inside are executed twice like printf function meanwhile character array of 6 size taking only 3 inputs:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main() {
int i = 0;
char name[6];
for (int i = 0; i < 5; ++i)
{
printf("Enter the character in name array");
scanf("%c", &name[i]);
}
printf("%s", name);
return 0;
}
when you define an array of characters ,in the last element of array you should place \0 to terminate string. so you can scan 5 characters as you do ,but you should add \0 at the end of your string.
also you should add space to your scanf like this scanf(" %c", &name[i]); ,otherwise you will take \n as a character of your string after each time you use enter.(that is reason of problem you explained)
look
int main() {
int i = 0;
char name[6];
for (i = 0; i < 5; ++i)
{
printf("Enter the character in name array");
scanf(" %c", &name[i]);
}
name[i] = '\0';
printf("%s", name);
return 0;
}
also note that ,I have removed int i from here for (int i = 0; i < 5; ++i) , otherwise this i would be only visible in for loop block and out side of it, because of int i = 0; \0 would be placed in name[0] ,and string would be lost.
or use scanf("%6s", name) as #Eraklon said in comments.
Related
I tried to scan and print the characters of array using below code but input characters are not matching with output characters
#include <stdio.h>
int main() {
char s[10];
int i, n;
printf("enter the value of n:\n");
scanf("%d", &n);
printf("start entering the characters:\n");
for (i = 0; i < n; i++) {
scanf("%c", &s[i]);
}
for (i = 0; i < n; i++) {
printf("%c", s[i]);
}
return 0;
}
OUTPUT
enter the value of n:
5
start entering the characters:
ABCDE(scanf values)
ABCD(printf values)
Can anyone please clarify my doubt why is the output not matching with input
Since you are wanting to read data into a character array with "scanf" you probably could just reference the string identifier instead and simplify things. Following are a few tweaks to your code that still inputs the data and prints it back out.
#include <stdio.h>
#include <string.h>
int main()
{
char s[10];
int i, n;
printf("enter the value of n:\n");
scanf("%d", &n);
printf("start entering the characters:\n");
scanf("%s", s); /* In lieu of using a loop */
if (strlen(s) < n) /* Just in case less characters are entered than was noted */
n = strlen(s);
for (i = 0; i < n; i++)
{
printf("%c", s[i]);
}
printf("\n");
return 0;
}
The program just scans in the complete string instead of a character at a time. Also, I included the "<string.h> file so as to use functions such as "strlen" (get the length of the string) to provide a bit more robustness to the code. Running the program netted the same character set that was entered.
:~/C_Programs/Console/InputOutput/bin/Release$ ./InputOutput
enter the value of n:
7
start entering the characters:
ABCDEFG
ABCDEFG
You might give that a try.
Regards.
I'm struggling to copy a string within an array at a given index to another array of strings, any suggestions? When trying to print out the value of tempVal at any given index, it doesn't return anything.
#include <stdio.h>
#include <string.h>
int main(void) {
const int NUM_VALS = 20;
int i;
int matchCount = 0;
int actualInput;
scanf("%d", &actualInput);
char userString[actualInput][NUM_VALS];
char tempVal[actualInput][NUM_VALS];
for (i = 0; i < actualInput; ++i) {
scanf("%s", userString[i]);
// printf("%s", userString[i]);
strncpy(userString[i], tempVal[i], strlen(userString[i])); // < -- Not sure how to make work
printf("%s", tempVal[i]); // <-- Doesn't output anything?
}
return 0;
}
use the function which will limit the number of chars read and place the terminatins zero as well
for (int i = 0; i < actualInput; ++i) {
fgets(userString[i], NUM_VALS, stdin);
strcpy(tempVal[i], userString[i]); // < -- Not sure how to make work
printf("%s\n", tempVal[i]); // <-- Doesn't output anything?
}
It is no wonder why you got no appropriate output because with the provided code you high-probably will get a Segmentation fault. Beside this, there are several issues in the code. To explain them all and also answer the heading question would explode the frame. You can see how I corrected the code in my manner below.
char* strcpy ( char* destination, const char* source )
strcpy is a potential risk for causing buffer overflow if the destination char buffer is not large enough to hold the string to be copied by source. This in your case okay, because each buffers, userString[i] and tempVal[i], have the same capacity (amount of char elements), but if the code changes it could be harmful.
Note that you also should limit the amount of input characters when you catch the string from stdin. For this reason, fgets() is safer than scanf(), since it explicitly requires a maximum amount of characters to read.
char* strncpy ( char* destination, const char* source, size_t num );
strncpy fails to append a terminating null character if the first num characters of the source string do not contain a terminating \0.
Rather use snprintf() which is safe to 1. proofs the size of the destination buffer and limits the amount of characters to read and 2. always appends a null character (assuming the scan process was successful and no errors occurred):
#include <stdio.h>
#include <string.h>
int main(void) {
const int NUM_VALS = 20;
int i;
int s_num;
printf("Enter number of strings in array: ");
scanf("%d", &s_num);
getchar();
char userString[s_num][NUM_VALS];
char tempVal[s_num][NUM_VALS];
for (i = 0; i < s_num; ++i) {
printf("Enter string at userString[%d]: ",i);
if(fgets(userString[i],NUM_VALS, stdin) == NULL)
{
// error handling
if(ferror(stdin))
{
// handle I/O error.
}
else if(feof(stdin))
{
// end of file is reached.
}
}
else
userString[i][strcspn(userString[i], "\n")] = 0;
//printf("%s", userString[i]);
}
printf("\n");
for (i = 0; i < s_num; ++i) {
if(snprintf(tempVal[i], sizeof(tempVal[i]), "%s", userString[i]) < 0)
{
// error handling
fprintf(stderr,"Encoding error occurred!");
}
printf("tempValue[%d]: %s\n", i, tempVal[i]);
}
return 0;
}
Output at a test run:
Enter number of strings in array: 3
Enter string at userString[0]: hello
Enter string at userString[1]: world
Enter string at userString[2]: test
tempValue[0]: hello
tempValue[1]: world
tempValue[2]: test
Sorry guys,
I am taking a class and new to C. I was able to figure out how to solve my problem. I appreciate the suggestions for fixing the code, unfortunately they are beyond the scope of what I have learned in my intro course. I had to find word frequencies using a string array and for loops. Here is the complete working code:
#include <stdio.h>
#include <string.h>
int main(void) {
const int NUM_VALS = 20;
int i;
int j;
int matchCount = 0;
int actualInput;
scanf("%d", &actualInput);
char userString[actualInput][NUM_VALS];
char tempVal[actualInput][NUM_VALS];
for (i = 0; i < actualInput; ++i) {
scanf("%s", userString[i]);
strcpy(tempVal[i], userString[i]);
// printf("%s\n", userString[i]);
// printf("%s\n", tempVal[i]);
}
for (i = 0; i < actualInput; ++i) {
matchCount = 0;
for (j = 0; j < actualInput; ++j) {
if (strcmp(userString[i], tempVal[j]) == 0) {
matchCount++;
}
}
printf("%s %d\n", userString[i], matchCount);
}
return 0;
}
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.
I worked out this problem using what I learned from chapter 6 (current program). My original idea was to print and scan the values into the array with a loop and them print the values of the array, but I have not been able to make it work (commented section under main function). The program just prints newlines (the program prints the letter but I have to press enter to get the next letter). The commented section in the program within the main function is the idea of what I want to do. I included the program below and I thank you in advance for your help.
//This is a program to create an array of 26 elements, store
//26 lowercase letters starting with a, and to print them.
//C Primer Plus Chapter 6 programming exercise 1
#include <stdio.h>
#define SIZE 26
int main(void)
{
char array[SIZE];
char ch;
int index;
printf("Please enter letters a to z.\n");
for(index = 0; index < SIZE; index++)
scanf("%c", &array[index]);
for(index = 0; index < SIZE; index++)
printf("%c", array[index]);
//for(ch = 'a', index = 0; ch < ('a' + SIZE); ch++, index++)
//{ printf("%c", ch);
// scanf("%c", &array[index]);
//}
//for(index = 0; index < SIZE; index++)
// printf("%c", array[index]);
return 0;
}
The problem here is that
When you enter the character and then you press enter, you input two characters. One is the alphabetic character you enter and the other is the \n. That's why you get what you see. Solution is to consume the white space charcaters ..which is done by putting the ' ' in the scanf.
scanf(" %c", &array[index]);
^
Why it works?
Quoting the standard- 7.21.6.2
A directive composed of white-space character(s) is executed by
reading input up to the first non-white-space character (which remains
unread), or until no more characters can be read. The directive never
fails.
Example code:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 6
int main(void)
{
char array[SIZE];
int index;
printf("Please enter letters a to z.\n");
for(index = 0; index < SIZE; index++)
if( scanf(" %c", &array[index]) != 1){
fprintf(stderr,"%s\n","Error in input");
exit(1);
}
else {
printf("read: %c\n",array[index]);
}
for(index = 0; index < SIZE; index++)
printf("%c", array[index]);
putchar('\n');
return 0;
}
I'm new to C and have been set the following problem. I am to write a program where a string can be entered and stored, I should then enter two integer values which will then be used to remove characters from the string, afterwards the result should be printed. Once the program works it should be converted into a function.
I have created a program that will split the entered string into two strings which store the chars I want to keep in two buffers, afterwards the two strings are concatenated to give the resultant edited string. The problem I am having is that when I print the edited string I get random characters at the end and sometimes in between the two strings and I think it's because the strings are not being null terminated correctly. I hope that someone is able to help, Thanks :)
#include <stdio.h>
#include <string.h>
int main ()
{
char string [25];
char buffer1 [25];
char buffer2 [25];
int start;
int remove;
int i;
int finish;
int size;
int numbercopy;
int A, B, C;
printf("Enter a string: ");
gets(string);
printf("\nEnter a starting character position: ");
scanf("%d", &start);
printf("\nHow many characters would you like to remove? ");
scanf("%d", &remove);
finish = (start+remove);
size = strlen(string);
numbercopy = (size-finish);
strncpy(&buffer1[0], &string[0], start);
buffer1[start] = '\0';
strncpy(&buffer2[0], &string[finish], numbercopy);
buffer2[numbercopy] = '\0';
A = strlen(buffer1);
B = strlen(buffer2);
C = (A+B);
strcat(buffer1, buffer2);buffer1[C] = '\0';
for (i=0; i<25; i++)
{
printf("%c", buffer1[i]);
}
return 0;
}
Since it is a string, you do not need to print it character by character. Also, the loop indicates that only 25 char strings will be printed. If a string (buffer1) is shorter in length(<25), garbage values will be printed, if a string is is larger (>25), some chars will not be printed.
Change this:
for (i=0; i<25; i++)
{
printf("%c", buffer1[i]);
}
to this:
printf("%s", buffer1);