How to input two strings separated by new line in C - c

How can I input 2 strings which are separated by a new line?
My Problem:
First I need to give how many strings I need to get and then I need to get those strings then display it.
I tried this:
Code:
#include <stdio.h>
#include <string.h>
int main()
{
int n,i = 0;
scanf("%d", &n);
char arr[n][100];
for(int i = 0; i < n; i++)
{
scanf("%[^\n]s", arr[i]);
}
for(int i = 0; i < n; i++)
{
printf("%s\n", arr[i]);
}
return 0;
}
My Input is :
2 I am
Aravind
My Output is:
I am
รพ
First Line I got correct one but second line it shows some garbage value. Help me to solve this.

You have two major problems:
The "%[" format ends with the closing "]", there should be no "s" at the end.
The "%[" format doesn't skip leading space, like that newline which will be present after the first line you read.
Both these issues can be easily solve by using fgets to read whole lines instead.

You already have suggestions to not use scanf. However, if you 'must' use scanf then you can consider the following approach:
For dynamic memory allocation you should use malloc
the newline character stays in the stdin and hence needs to be flushed or handled/ignored
Here is the updated code.
int main()
{
int n,i = 0;
scanf("%d", &n);
scanf("%*[\n]");
/*this will read the \n in stdin and not store it anywhere. So the next call to
* scanf will not be interfered with */
char **inputs;
inputs = malloc(n * sizeof(char *));
for (i = 0; i < n; i++)
{
inputs[i] = malloc(100 * sizeof(char));
}
for(i = 0; i < n; i++)
{
scanf("%*[\n]");
scanf("%100[^\n]", inputs[i]);
}
for(i = 0; i < n; i++)
{
printf("%s\n", inputs[i]);
}
return 0;
}

use gets(arr[i]) instead of scanf.

Related

C reading a file of binary numbers drops first char

Can anyone help me understand why the first char read from the file is dropped when I increase the file size to be > 19 rows?
When I run this with < 20 rows it works perfect, reads the input and dumps it. when I add a 20th row the first row of input drops the leading char when I print the array.
Im lost. :)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
int i, j = 0;
FILE *pFile;
char string[20][12];
char file_contents_resultset[20][12];
pFile = fopen("sonar.txt", "r");
if (pFile == NULL)
{
printf ("error opening file");
return 0;
}
// Load 20 row of input into in an array and store a copy
for (i = 0; i < 20; i++)
{
fscanf (pFile, "%12s", &string[i]);
strcpy (file_contents_resultset[i], string[i]);
}
//Dump the first 5 rows of the array
printf ("Dump array contents \n");
for (i = 0; i < 5; i++)
{
for (j = 0; j < 12; j++)
{
printf ("%c", file_contents_resultset[i][j]);
}
printf ("\n");
}
fclose (pFile);
return 0;
};
This is my input file.
000110010001
101000110000
000110010111
100011100010
111001100001
001010001010
010100100101
011000010000
111111011010
001111011101
011011010010
001100010101
001010101100
000000000000
100010111111
100100110011
111100100001
011110001110
000110100101
011101111001
and this is the output
Dump array contents
00110010001
101000110000
000110010111
100011100010
111001100001
and this is the output if I delete the 20th row of input in the input file. Note the first char is no longer dropped.
Dump array contents
000110010001
101000110000
000110010111
100011100010
111001100001
Your one of the arrays you use for reading is redundant. You can use only string[][] or only file_contents_resultset[][].
I found that your problem is in the strcpy() call. Reading from the buffer is fine, but strcpy() seems to copy a blank character in the memory location of file_contents_resultset[0][0].
So to fix it by keeping as much of the program intact i did:
// ...
// stores only one row at a time
char string[12];
// ...
for (int i = 0; i < 20; i++) {
fscanf(pFile, "%12s", &string);
strcpy(file_contents_resultset[i], string);
}
// ...
}
If you want to be more concise and save memory, you can remove string altogether and just write:
// ...
// char string[12];
char file_contents_resultset[20][12];
// ...
// brackets in loops and other blocks can be omitted
// if the block is just 1 line long.
for (int i = 0; i < 20; i++)
fscanf(pFile, "%12s", &file_contents_resultset[20][12]);
// ...

printing characters using array in c language?

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.

Runtime initialization of character array in C using for loop

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.

Use strcpy() or strncpy() for array of strings?

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

How to read multiple strings in C one in a line, each containing spaces?

I allocated a 2D array of characters, and while reading strings with no whitespaces between, the code is working fine. When I read them with whitespaces, I'm facing a bug. How do I read all N number of Strings, each in a single line, each one containing whitespaces.
Example input:
Enter total number of Strings : 3
Enter all the 3 Strings :
John Doe
Jane Doe
Trad Braversy
My code:
// Code to enter the total number of Strings :
int N;
printf("\n\tEnter the total number of Strings : ");
scanf("%d", &N);
// Code for allocating initial memory to them :
char** strings = (char**)malloc(N * sizeof(char*));
for (int i = 0; i < N; ++i) {
strings[i] = (char*)malloc(1024 * sizeof(char));
}
// Code for entering all the N strings :
printf("\n\tEnter all the %d Strings :\n", N);
for (int i = 0; i < N; ++i) {
gets(strings[i]);
}
// Code to reallocate the memory according to the entered length :
for (int i = 0; i < N; ++i) {
strings[i] = (char*)realloc(strings[i], strlen(strings[i]) + 1);
}
A few observations:
It's safer to read a full line of text, then parse out the integer from that, rather than doing scanf() for a single integer. This is because the latter leaves the newline in the stream, which can confuse later reads.
There's no real point in using malloc() to do dynamic memory allocation for this, you can use a VLA:
char strings[N][1024];
Note that using a capital-only symbol for a runtime variable is stylistically strange in C.
Then, it's much better to use fgets(), it's safer and just better:
for (int i = 0; i < N; ++i)
{
if (fgets(strings[i], sizeof strings[i], stdin) == NULL)
{
fprintf(stderr, "**Read error on string %d\n", i);
exit(1);
}
}
And as always, be prepared that I/O can fail, and try to handle that.

Resources