the objective of my question is very simple. The first input that I get from the user is n (number of test cases). For each test case, the program will scan a string input from the user. And each of these strings I will process separately.
The question here is how can I get string inputs and process them separately in C language??? The idea is similar to the dictionary concept where we can have many words which are individual arrays inside one big array.
The program I have written so far:
#include <stdio.h>
#define max 100
int main (){
int n; // number of testcases
char str [100];
scanf ("%d\n",&n);
for (int i =0;i <n;i++){
scanf ("%s",&str [i]);
}
getchar ();
return 0;
}
Can someone suggest what should be done?
The input should be something like this:
Input 1:
3
Shoe
Horse
House
Input 2:
2
Flower
Bee
here 3 and 2 are the values of n, the number of test cases.
First of all, Don't be confused between "string" in C++ , and "Character Array" in C.
Since your question is based on C language, I will be answering according to that...
#include <stdio.h>
int main (){
int n; // number of testcases
char str [100][100] ; // many words , as individual arrays inside one big array
scanf ("%d\n",&n);
for (int i =0;i <n;i++){
scanf ("%s",str[i]); // since you are taking string , not character
}
// Now if you want to access i'th word you can do like
for(int i = 0 ; i < n; i++)
printf("%s\n" , str[i]);
getchar ();
return 0;
}
Now here instead of using a two-dimensional array, you can also use a one-dimensional array and separate two words by spaces, and store each word's starting position in some another array. (which is lot of implementation).
First of all yours is not C program, as you can't declare variable inside FOR loop in C, secondly have created a prototype using Pointer to Pointer, storing character array in matrix style datastructure, here is the code :-
#include <stdio.h>
#include <stdlib.h>
#define max 100
int main (){
int n,i; // number of testcases
char str [100];
char **strArray;
scanf ("%d",&n);
strArray = (char **) malloc(n);
for (i =0;i <n;i++){
(strArray)[i] = (char *) malloc(sizeof(char)*100);
scanf ("%s",(strArray)[i]);
}
for (i =0;i <n;i++){
printf("%s\n",(strArray)[i]);
free((strArray)[i]);
}
getchar ();
return 0;
}
#include <stdio.h>
#define MAX 100 // poorly named
int n=0; // number of testcases
char** strs=0;
void releaseMemory() // don't forget to release memory when done
{
int counter; // a better name
if (strs != 0)
{
for (counter=0; counter<n; counter++)
{
if (strs[counter] != 0)
free(strs[counter]);
}
free(strs);
}
}
int main ()
{
int counter; // a better name
scanf("%d\n",&n);
strs = (char**) calloc(n,sizeof(char*));
if (strs == 0)
{
printf("outer allocation failed!")
return -1;
}
for (counter=0; counter<n; counter++)
{
strs[counter] = (char*) malloc(MAX*sizeof(char));
if (strs[counter] == 0)
{
printf("allocate buffer %d failed!",counter)
releaseMemory();
return -1;
}
scanf("%s",&strs[counter]); // better hope the input is less than MAX!!
// N.B. - this doesn't limit input to one word, use validation to handle that
}
getchar();
// do whatever you need to with the data
releaseMemory();
return 0;
}
Related
So I was working on an assignment for school, and had written up a variation of this code:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX 100
// This program takes an input of strings and prints them out with a new line separating each one.
int main() {
char *WordArray[MAX]; //initializing variables
int i = 0;
int count = 0;
printf("enter up to 100 words, that are 20 characters maximum \n");
for (i = 0; i <100; i++){ //runs while there's less than 100 inputs
char Array[1];
scanf("%s",Array); //stores string in the array
if (strcmp(Array, "STOP") == 0) { //compares the string with stop, and if it is, it breaks out of the loop
break;
}
WordArray[i]=Array; //stores the string in the pointer array
}
printf("The output is\n");
for (count = 0; count<i; count++){ //counts up to the amount of words stored
printf("%s\n",WordArray[count]); //outputs each pointer string
}
}
and I noticed that the output was printing "STOP" instead of the values stored. Anyone have any answers to why and/or how to fix it? I know one of the methods is to switch to a 2D array instead of using pointers, but I'm still baffled as to why a program like this wouldn't work.
Your char Array[1]; isn't large enough to store any but an empty string. Also, when it works, every pointer will point to the same string, which will be the last entry you made. This makes some corrections where commented.
#include <stdio.h>
#include <stdlib.h> // instead of ctype.h
#include <string.h>
#define MAX 100
// This program takes an input of strings and prints them out with a new line separating each one.
int main() {
char *WordArray[MAX];
int i = 0;
int count = 0;
printf("enter up to 100 words, that are 20 characters maximum \n");
for (i = 0; i <100; i++){
char Array[21]; // increase size of array
scanf("%20s",Array); // limit entry length
if (strcmp(Array, "STOP") == 0) {
break;
}
WordArray[i] = strdup(Array); // allocate memory for and copy string
}
printf("The output is\n");
for (count = 0; count<i; count++){
printf("%s\n",WordArray[count]);
}
// free each string's memory
for (count = 0; count<i; count++){
free(WordArray[count]);
}
}
Program output:
enter up to 100 words, that are 20 characters maximum
one two three STOP
The output is
one
two
three
Edit: note that your code contains another undefined behaviour besides the too-short string char Array[1] which is that you dereference the pointer you stored in char *WordArray[MAX];. The scope of Array is inside the for loop, and theoretically ceases to exist after the loop completes, so the pointer you store is invalid. Here, the word entered is duplicated with strdup so that doesn't apply.
I'm making a program where user enters grades (1 to 5) and then the grade gets added to array for later inspection. When user enters letter "s", the program closes. When ran my program crashes, why?
#include <stdio.h>
#include <stdlib.h>
int i;
int grade[50];
char *num[20];
int enter();
int enter()
{
for (i=0; i<10; i++) {
printf("\nEnter grade:\nPress [s] to close program\n");
scanf("%s",&num[i]);
if (strcmp(num[i],"s") == 0) {
break;
} else {
grade[i] = atoi(num[i]);
}
}
}
int main()
{
enter();
for (i=0; i<10; i++) {
printf("\n%d",grade[i]);
}
return 0;
}
remove ' * ' from num[20] declaration, as you are declaring 20 character string pointers, so reading and comparing values with num[i] will cause error.
Besides, you just nead a simple string to get the grade.
The reason why program crashed is that num is a pointer array, the element of num can not pointer to valid memory which used to store the string you inputed.
you can change char *num[10] to char num[10][12] and 'scanf("%s", &num[i])to scanf("%s", num[i]), and that everything will be OK.
Of course, you can use malloc to dynamic alloc memory for each element in num, like:
`for(i = 0; i < 10; i ++){
num[i] = (char*)malloc(sizeof(char) * 12);
}
`
Even thought, you must change scanf("%s", &num[i]) to scanf("%s", num[i]);
Finally, you can not forget to free the memory you just dynamic malloc.
Wondering how store different strings in an array.
For example a user would input 'qwe' and the program would then store that in an array variable[0]. Entering another string would then store it as variable[1] and so on
int
main(int argc, char *argv[]) {
char variable[1000];
int i;
printf("enter a variable\n");
scanf("%s", variable);
for (i = 0; ??? ;i++) {
printf("The variable entered was: %s\n",variable[i]);
}
return 0;
Im new to C so I have no idea what im doing. but thats what I have came up with so far and was wondering if I could get some help with filling in the rest
Thanks!
You can use 2D array to store multiple strings. For 10 strings each of length 100
char variable[10][100];
printf("Enter Strings\n");
for (int i = 0; i < 10 ;i++)
scanf("%100s", variable[i]);
Better to use fgets to read string.
fgets(variable[i], sizeof(variable[i]), stdin);
You can also use dynamic memory allocation by using an array of pointers to char.
The most efficient way is to have an array of character pointers and allocate memory for them as needed:
char *strings[10];
int main(int ac, char *av[]) {
memset(strings, 0, 10 * sizeof(char *));
for (int i = 0; i < 10; i += 1) {
char ins[100];
scanf("%100s", ins);
strings[i] = malloc(strlen(ins) + 1);
if (strings[i]) {
strcpy(strings[i], ins);
}
}
}
variable[0] has just stored first letter of string. If you want to store multiple strings in an array you can use 2D array.
it has structure like
arr[3][100] = { "hello","world", "there"}
and you can access them as
printf("%s", arr[0]); one by one.
scanf returns number of successful readed parameters;
use 2D array for string-array
Never go out of bounds array
#include <stdio.h>
//Use defines or constants!
#define NUM_STRINGS 10
#define MAX_LENGTH_OFSTRING 1000
int main() {
char variable[NUM_STRINGS][MAX_LENGTH_OFSTRING +1 /*for '\0' Null Character */];
int i = 0;
printf("enter a variable\n");
while(scanf("%s", variable[i]) > 0){//if you print Ctrl+Z then program finish work. Do not write more than MAX_LENGTH_OFSTRING symbols
printf("The variable entered was: %s\n",variable[i]);
i++;
if(i >= NUM_STRINGS)
break;
}
return 0;
}
I would like to count the number of elements in an integer array(sized, like: array[1000]) after input without counting manually while inputting(using scanf() which is = number of arguments passed to scanf).Though int arrays are not null terminated as well as scanf() cannot be used like getchar() or gets() and no availale function like strlen() for int arrays,is it possible to write a C program to prompt the user to input as many numbers as he wishes and the program will count them(total arguments passed to scanf()) and print the maximum using arrays or pointers?
Without having a termination value, you will have to count the inputs as they are made. You could do this by defining a struct to hold the array. Your program does not know how many integers you will enter, and this code allocates more memory when the array is full, keeping track of the array size and elements used.
#include <stdio.h>
#include <stdlib.h>
#define ARRAY_STEP 10 // increment in array size
typedef struct {
int maxlen; // capacity of array
int length; // elements used
int *array; // the array pointer
} istruct;
int main(void) {
istruct intarr = {0}; // empty array
int i;
printf ("Enter some integers:\n");
while (scanf("%d", &i) == 1) {
if (intarr.length >= intarr.maxlen) {
intarr.maxlen += ARRAY_STEP; // increase array size
intarr.array = realloc(intarr.array, intarr.maxlen * sizeof(int));
if (intarr.array == NULL) {
printf("Memory allocation error\n");
exit (1);
}
}
intarr.array[intarr.length++] = i;
}
printf ("You entered:\n");
for (i=0; i<intarr.length; i++)
printf ("%-10d", intarr.array[i]);
printf ("\n");
if (intarr.array)
free(intarr.array);
return 0;
}
strlen() iterates on the character array until the C string termination character (ASCII \0) is encountered. So it is COUNTING the elements. If you want to do that for an int array I guess you could also have a reserved 'terminator' value for your array, make room for it (allocate one more int in your array for the terminator) and implement your own int_array_len() similar to strlen. However, in your case counting the elements while inputting them seems like a much better way to go.
Smart vertion:
#include <stdio.h>
int main()
{
double a[100000],mx=0;
int i,j,c=0;
printf("Enter as many numbers as you wish . Press Ctrl+D or any character to stop inputting :\n");
/*for(i=0;i<100000;i++)
a[i]=0;*/
for(i=0;i<100000;i++)
{
if((scanf("%lf",&a[i]))==1)
c++;
//else break;
}
for(j=0;j<c;j++)
{
if(a[j]>mx) mx=a[j];
}
printf("You have inserted %d values and the maximum is:%g",c,mx);
return 0;
}
It's pretty simple.
just declare of your desired "initial size". And keep checking if input is a valid integer or not.
if((scanf("%d",&a[i]))==1) this would be true if and only if the input is a valid integer. hence the moment the input is not an int, it exits the loop. You can count the number of input values within the same loop and also the max values.
Here is the code:
#include <stdio.h>
#include<limits.h>
int main()
{
int a[100],max = INT_MIN;
int i,j,count=0;
printf("Start Entering the integers... Give any non-integer input to stop:\n");
for(i=0;i<100;i++)
{
if((scanf("%d",&a[i]))==1) {
count++;
if(a[i]>max) {
max = a[i];
}
}
else
break;
}
printf("number of input values: %d;\nThe maximum input value: %d",count,max);
return 0;
}
I am having trouble storing strings into a 2d array using scanf.
To illustrate, this is the input the program accepts:
p2/src/stuff:5:
p3/src/stuff:5:
p4/src/stuff:6:
So I want to be able to split the strings and numbers by colons and store them separately. So ideally, my 2d array would look like this for strings:
[["p2/src/stuff"], ["p3/src/stuff"], ["p4/src/stuff"]]
Numbers can be stored in a 1d array.
Here is what I have so far:
int main() {
char *str;
char *i;
int n = 1;
while (n == 1) {
n = scanf("%m[^':']:%m[^':']:", &str, &i);
}
printf("# inputs read: %d\n", n);
printf("%s\n", str);
printf("%s\n", i);
}
Here it only prints the first line:
p2/src/stuff
5
Should I have an iterator that dose pointer arithmetic? I'm not familiar with pointer arithmetic.
scanf returns the number of items scanned. In this case it would be 2 instead of 1. Here a return of 1 would indicate a problem during the scan.
The %m specifier allocates memory to the pointers. Using a single pair of pointers, they should be freed in eadh iteration of the loop. You could use an array of pointers to store each of the inputs.
The scanset does not need the single quotes [^':']. If you are scanning for all characters that are not a colon [^:] will work.
EOF will terminate the while loop so if you are reading from a file, it will stop at the end of the file. Reading from stdin could be terminated using Ctrl+D (Linux) or Ctrl+Z (Windows).
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char *str;
char *i;
int n;
while ( ( n = scanf("%m[^:]:%m[^:]:", &str, &i)) == 2) {
printf("# inputs read: %d\n", n);
printf("%s\n", str);
printf("%s\n", i);
free ( str);
free ( i);
}
return 0;
}
EDIT:
This uses an array of pointers to collect several inputs to the str and i arrays.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char *str[10];// array of pointers
char *i[10];
int each = 0;
int loop = 0;
int n = 0;
while ( ( n = scanf("%m[^:]:%m[^:]:", &str[each], &i[each])) == 2) {
printf("# inputs read: %d\n", n);
printf("%s\n", str[each]);
printf("%s\n", i[each]);
each++;
if ( each > 9) {
break;//too many inputs for array size
}
}
for ( loop = 0; loop < each; loop++) {
printf ( "str[%d]=%s\n", loop, str[loop]);//print all the str inputs
}
for ( loop = 0; loop < each; loop++) {
printf ( "i[%d]=%s\n", loop, i[loop]);//print all the i inputs
}
for ( loop = 0; loop < each; loop++) {//free memory
free ( str[loop]);
free ( i[loop]);
}
return 0;
}
You have a few issues here.
First, while you should be using character pointers, you never allocate any memory for them. Next, when you use scanf, you should not be passing the address of the pointers but the pointers themselves. This is an easy mistake to make since you must pass the address when using scanf with integer types.
int main() {
char str[255];
char i[255];
int n = 1;
while (n == 1) {
n = scanf("%m[^':']:%m[^':']:", str, i);
}
printf("# inputs read: %d\n", n);
printf("%s\n", str);
printf("%s\n", i);
}