This question already has answers here:
How can I read an input string of unknown length?
(11 answers)
Closed 4 years ago.
I am fairly new to C programming language. And I am getting stuck at finding the size of string the user inputs.
A sample code is below:
char * input;
int main(){
printf("Enter the string : ");
scanf("%s\n", input);
int n = ( ) // this is where i put the size of input which i need at run time for my code to work
for (int i=0; i<n; i++){
// code here
// i create threads here
}
for (int i=0; i<n; i++){
// code here
// i join threads here
}
}
So, my problem is I can't find any answers at stack overflow which deals with the size of input above.
Any help will be appreciated.
strlen(char*)
In C, this is the function to find the length of a string
The following example shows the usage of strlen() function:
#include <stdio.h>
#include <string.h>
int main () {
char str[50];
int len;
strcpy(str, "LOL");
len = strlen(str);
printf("Length of |%s| is |%d|\n", str, len);
return(0);
}
And, if you want find lenght without strlen()
#include <stdio.h>
int main()
{
char s[1000], i;
printf("Enter a string: ");
scanf("%s", s);
for(i = 0; s[i] != '\0'; ++i);
printf("Length of string: %d", i);
return 0;
}
Related
This question already has answers here:
How can I correctly assign a new string value?
(4 answers)
Closed 9 months ago.
The community reviewed whether to reopen this question 9 months ago and left it closed:
Original close reason(s) were not resolved
Suppose I accept an input that is a string "I am a beginner in programming". What I want to do is store that input per word into a 2d array. How do I translate that to code?
I am new to programming so I am not really that familiar with it.
I tried coding it this way and perhaps the error is in the inner loop part. I think it repeats storing the "I" after it breaks out from the inner loop and having variable col initialized again? But I can't really think of a way to correct it.
int main(void) {
const int SIZE1=20;
const int SIZE2=30;
char string[100];
char string2[SIZE1][SIZE2];
int row, col;
printf("Input a string: ");
gets(string);
for(row=0; row<SIZE1; row++)
{
for(col=0; col<SIZE2; col++)
{
if(string[col]==' ')
break;
else
string2[row][col]=string[col];
}
}
printf("%s\n", string2[0]);
printf("%s\n", string2[1]);
printf("%s\n", string2[2]);
printf("%s\n", string2[3]);
printf("%s\n", string2[4]);
printf("%s\n", string2[5]);
printf("%s\n", string2[6]);
return 0;
}
You can use strtok function which breaks string into a series of tokens using the delimiter (A Space Character in this case).
#include <stdio.h>
#include <string.h>
int main(void) {
char myText[] = "I am a beginner in programming";
char *p = strtok(myText, " "); // Get The First Token
char *myTextArr[6];
int i = 0;
while (p != NULL) {
myTextArr[i++] = p;
p = strtok(NULL, " "); // Walk through other tokens
}
for (i = 0; i < 6; ++i) {
printf("%s\n", myTextArr[i]);
}
return 0;
}
Output:
I
am
a
beginner
in
programming
This question already has answers here:
How should character arrays be used as strings?
(4 answers)
Closed 11 months ago.
#include <stdio.h>
int main()
{
FILE *fisier;
fisier = fopen("cnp.txt", "r");
int cnpuri = 0;
char cnp[10][13];
while(1){
fscanf(fisier, "%s", cnp[cnpuri]);
cnpuri++;
if(feof(fisier))
break;
}
int i;
for(i = 0; i < cnpuri; i++){
printf("%s \n", cnp[i]);
}
fclose(fisier);
return 0;
}
This is the text I'm reading:
1234567890123
1763578126765
4156156546489
5749684631654
5498654168763
And this is what it shows in terminal:
12345678901231763578126765415615654648957496846316545498654168763
1763578126765415615654648957496846316545498654168763
415615654648957496846316545498654168763
57496846316545498654168763
5498654168763
The problem is that the second size of the array
char cnp[10][13];
is not large enough to store the terminating zero character of entered strings.
Declare it at least like
char cnp[10][14];
Also change the while loop the following way
while( cnpuri < 10 && fscanf(fisier, "%s", cnp[cnpuri]) == 1)
{
cnpuri++;
}
This question already has answers here:
How do you reverse a string in place in C or C++?
(21 answers)
Reverse string with pointers? [duplicate]
(4 answers)
Closed 2 years ago.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void str_prn(char **);
int main(void)
{
char temp[80];
char **str;
int max;
int i;
printf("Number of Strings : ");
scanf("%d", &max);
str = (char **)malloc((max+1)*sizeof(char*));
i=0;
while(1)
{
printf("Input the string : ");
scanf("%s",temp);
str[i] = (char*)malloc(strlen(temp)+1);
strcpy(str[i],temp);
i++;
if(i ==max)
{
printf("Complete!!\n\n");
break;
}
}
str_prn(str);
i=0;
while(str[i]!=0)
{
free(str[i]);
++i;
}
free(str);
system("PAUSE");
return 0;
}
void str_prn(char **sp)
{
int i, len=0;
char *reversedSp;
len = strlen(*sp);
while(*sp !=0)len++;
{
for(i=0;i<len;i++)
{
reversedSp = *sp
}
}
return;
}
I want to get the result of input strings reversed.
I mean if I get "abcdeqwerty" the result should be result should be "edcbaytrewq"
First I used strrev func but my professor said not to use strrev.
So I tried to deal with the matter by using for loop.
In the function str_prn, How can I revise it to work?
You could try tou count the length of your string, and then start from the end...
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;
}
A program for merging two words:
#include<stdio.h>
int main()
{
char s1[10],s2[10],s3[10];
int i,j,n=1;
for(i=0;i<n;i++)
scanf("%s",&s1[i]);
for(i=0;i<n;i++)
scanf("%s",&s2[i]);
for(j=0;s2[i];j++)
{
s3[i] = s1[i]+s2[j];
}
printf("%s",s3);
return 0;
}
I'm getting a runtime error in this program. Could anyone help me to correct it or point out what the error is?
for(i=0;i<n;i++)
scanf("%s",&s1[i]);
for(i=0;i<n;i++)
scanf("%s",&s2[i]);
This is not how you read strings. Try this:
scanf("%s", s1);
scanf("%s", s2);
That's not perfect, but should work for a beginner.
scanf("%s",&s1[i]); does not do what you think it does. It seems to me you are confusing %s with %c. This is causing a buffer overflow. So read the documentation of scanf() format strings.
Then, don't use scanf() because it's unsafe and hard to use correctly. For getting user input, use fgets().
Your code have several problems:
You are using scanf in a wrong a way. It should be like scanf("%s", s1); same for s2.
To merge two strings you can use built-in function strcat which append its second argument to its first argument; just use it two times to merge your two strings in vector s3.
In conclusion, your code should look like:
#include<stdio.h>
#include <string.h>
int main()
{
char s1[10],s2[10],s3[20];
scanf("%s",s1);
scanf("%s",s2);
strcat(s3,s1);
strcat(s3,s2);
printf("%s",s3);
printf("\n");
return 0;
}
Just remember that your s3 vector must be sufficiently large to contain both your strings.
#include <stdio.h>
int main(void){
char s1[10], s2[10], s3[20];
int i, j, n=1;
scanf("%9s", s1);
scanf("%9s", s2);
sprintf(s3, "%s%s", s1, s2);
printf("%s\n",s3);
return 0;
}
You're probably doing a free online course "Programming, Data Structures & Algorithms" at https://onlinecourses.nptel.ac.in
Anyway, the answer to this is:
#include <stdio.h>
#include <string.h>
int main() {
char a[20], b[10], c;
int x[20];
int i,j,l,n,swap;
scanf("%s",a);
scanf("%s",b);
strcat(a,b);
l=strlen(a);
for(i=0; i<l; i++) {
n = a[i];
x[i] = n;
}
for(i=0; i<(l-1); i++) {
for(j=0; j<(l-i-1); j++) {
if(x[j]>x[j+1]) {
swap = x[j];
x[j] = x[j+1];
x[j+1] = swap;
}
}
}
for(i=0; i<l; i++) {
c = x[i];
printf("%c",c);
}
}
You should edit the question if you really meant this.
Okay first of all, if you declare like char arr[10]; then read like scanf("%s",arr);
So you read the two words like:
scanf("%s",s1);
scanf("%s",s2);
Okay, now to merge two words of length 10, first declare the result array to be twice of 10.
So here goes the full code:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int compare (const void * a, const void * b)
{
return ( *(char*)a - *(char*)b );
}
int main()
{
char s1[10],s2[10],s3[20];
scanf("%s",s1);
scanf("%s",s2);
strcpy(s3,s1); // copies content of s1 to s3
strcat(s3,s2); // merges to end of s3 the content of s2
qsort(s3,strlen(s3),sizeof(char),compare); //sorts s3
printf("%s",s3);
return 0;
}
See qsort().