I'm trying to scanf multiple ints from a string, but I don't know how many it will have, because it varies from case to case.
I want to scanf multiple numbers and put them in an array.
I've been trying to do it this way but it's not working...
Assuming I want to scan C numbers from the string "line".
for(a=0;a<c;a++)
sscanf(line, " %d ",&v[a]);
I wrote a piece of code to help you understand it more clearly.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
int v[10];
char buffer[4096];
char * line = NULL;
int i, j;
if(fgets(buffer, 4096, stdin) == NULL){
return -1;
}
for(i = 0, line = strtok(buffer, " "); i < 10; i++){
if(line == NULL){
break;
}
sscanf(line, "%d", &v[i]);
line = strtok(NULL, " ");
}
j = i;
for(i = 0; i < j; i++){
printf("%d\n", v[i]);
}
return 0;
}
[neo]:./a.out
1 2 3 4 5 9999
1
2
3
4
5
9999
Suppose you have enough space to store as much as integer.
char * c_num = NULL;
for(c_num = strtok(line, " \t\n"), a = 0; c_num != NULL && a < c; c_num = strtok(NULL, " \t\n"), a++){
v[a] = atoi(c_num);
}
I finally nailed it! Thanks for all your help guys ;)
f = fopen(argv[1],"r");
fgets(line,c,f);
line2 = strtok(line, " ");
while (line2 != NULL){
sscanf(line2, "%d",&v[i]);
line2=strtok(NULL, " ");
i++;
}
Related
I'm having trouble rewriting my code.
This is my program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char pole[100];
int i = 0;
char *token;
char *space = " \r\n";
while(fgets(pole, 100, stdin)){
int j = 0;
token = strtok(pole, space);
while (token != NULL){
if (strlen(token) > 0){
j++;
}
token = strtok(NULL, space);
}
if (strcmp(pole, "x") == 0 || strcmp(pole , "x\n") == 0){
break;
}
i += j;
}
for (int x = 0; x < i; x++){
printf("Word %d: \n", x);
}
return 0;
}
Input:
Hello I am human
Programming
Apple moon
x
Output:
Word 0:
Word 1:
Word 2:
Word 3:
Word 4:
Word 5:
Word 6:
But I want to write the number of strings at the beginning then the strings like this (without "x"):
3
Hello I am human
Programming
Apple moon
and get this
Word 0:
Word 1:
Word 2:
Word 3:
Word 4:
Word 5:
Word 6:
I've tried this to solve this problem, but it doesn't work
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char pole[100];
int i = 0;
int cislo;
int cislo2 = 0;
char *token;
char *space = " \r\n";
scanf("%d", &cislo);
while (cislo2 < cislo){
while(fgets(pole, 100, stdin)){
int j = 0;
token = strtok(pole, space);
while (token != NULL){
if (strlen(token) > 0){
j++;
}
token = strtok(NULL, space);
}
}
i += j;
break;
}
for (int x = 0; x < i; x++){
printf("Word %d: \n", x);
}
return 0;
}
I have no idea how to improve my program to get what I want. Please help me.
There are a few things:
You need to usewhile (cislo2 <= cislo) otherwise you'll be off by one.
Place i += j inside the inner while loop.
Why use a while loop if you break out anyway (replace the second while loop with an if)
Count up cislo2, otherwise you got yourself an infinite loop
Here is the full code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char pole[100];
int i = 0;
int cislo;
int cislo2 = 0;
char *token;
char *space = " \r\n";
scanf("%d", &cislo);
while (cislo2 <= cislo){
if (fgets(pole, 100, stdin)){
int j = 0;
token = strtok(pole, space);
while (token != NULL){
if (strlen(token) > 0){
j++;
}
token = strtok(NULL, space);
}
i += j;
}
cislo2++;
}
for (int x = 0; x < i; x++){
printf("Word %d: \n", x);
}
return 0;
}
So I have this program where it asks the user for a filename to read, and a filename to save the output to. This program basically counts the frequency of a letter inside the txt file. Here is the program...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
char letter[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ", FileName[50], SaveFile[50], print[256], stry[50], scount[50], point;
int i, j, count = 0;
FILE * readFile, *saveFile;
printf("Enter a file to read: ");
gets(FileName);
printf("Enter a filename to save results: ");
gets(SaveFile);
printf("Letter Frequency\n\n");
saveFile = fopen(SaveFile, "wb");
for(i = 0; i <= strlen(letter)-1; i++)
{
readFile = fopen(FileName, "r");
while(!feof(readFile))
{
fgets(print, 256, readFile);
for(j = 0; j <= strlen(print); j++)
{
if(toupper(print[j]) == toupper(letter[i]))
{
count++;
}
}
point = letter[i];
stry[0] = point;
sprintf(scount, "%d", count);
if(feof(readFile) && count > 0)
{
printf("%s %d\n", stry, count);
fprintf(saveFile, stry);
fprintf(saveFile, " ");
fprintf(saveFile, scount);
fprintf(saveFile, "\n");
}
}
count = 0;
}
fclose(readFile);
return 0;
}
I input a txt file named readme.txt that I modified. It contains
aaa
bbb
ccc
ddd
But when I run it, and used readme.txt to be read, the output is
A 3
B 3
C 3
D 6
The frequency of letter D must be only 3. I further modified the content of the readme.txt file, and figured out that value of the variable count is doubled when reading the last line. For example, the content of the txt file is
hello mama
hihihi
maria maria
woohoo
the output will be
A 6
E 1
H 6
I 5
L 2
M 4
O 9
R 2
W 2
I read my program so many times already, and I still can't find my wrong doings. I hope you can help me fix this problem. Your help will be very much appreciated!
EDIT:
This is what my code looks like after making the changes that were recommended in the comments section:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
char letter[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ", FileName[50], SaveFile[50], print[256], stry[50], scount[50], point;
int i, j, count = 0;
FILE * readFile, *saveFile;
printf("Enter a file to read: ");
gets(FileName);
printf("Enter a filename to save results: ");
gets(SaveFile);
printf("Letter Frequency\n\n");
saveFile = fopen(SaveFile, "wb");
for(i = 0; i < strlen(letter); i++){
readFile = fopen(FileName, "r");
while(fgets(print, 256, readFile) != NULL)
{
fgets(print, 256, readFile);
for(j = 0; j <= strlen(print); j++)
{
if(toupper(print[j]) == toupper(letter[i]))
{
count++;
}
}
point = letter[i];
stry[0] = point;
sprintf(scount, "%d", count);
if(feof(readFile) && count > 0)
{
printf("%s %d\n", stry, count);
fprintf(saveFile, stry);
fprintf(saveFile, " ");
fprintf(saveFile, scount);
fprintf(saveFile, "\n");
}
}
count = 0;
}
fclose(readFile);
return 0;
}
I have to code in an array that can count an element. For example, if the user enters a 2, 2, 2, 1,1 then the user wants to count the number 2 then the result will be ELEMENT is 2 and FREQUENCY is 3. but I have a problem with the parts of " ENTER THE NUMBER YOU WANT TO BE COUNTED". I use scanf but when I run it I cannot enter any number.
Here's my code:
void frequency()
{
system("cls");
int num;
int count=0;
printf("Enter a number you want to be count: \n ");
scanf("i%", &num);
printf(" ELEMENT | FREQUENCY \n ");
for (i = 0; i<=n; i++)
{
if (a[i]==a[num])
count++;
}
printf(" \n %i ", num);
printf(" \t\t");
printf("%i \n ", count);
getch();
}
Your program requires understanding on two parts:
Get input and split input by delimiter, which can be done by using strtok.
Algorithm for finding the duplicated elements in an array.
#include <stdio.h>
#include <string.h>
int main() {
frequency();
return 0;
}
void frequency() {
char str[100];
printf("Enter a number you want to be count: \n ");
gets(str);
int init_size = strlen(str);
char delim[] = " ";
char *ptr = strtok(str, delim);
char *pch;
int arr[20];
int count = 0;
int ncount, i, j;
int a[count], Freq[count];
while(ptr != NULL) {
/*printf("'%s'\n", ptr);*/
/*Converts the string argument str to an integer (type int)*/
arr[count] = atoi(ptr);
/*strtok accepts two strings - the first one is the string to split, the second one is a string containing all delimiters*/
ptr = strtok(NULL, delim);
/*Initialize frequency value to -1*/
Freq[count] = -1;
count += 1;
}
/*Count the frequency of each element*/
for (i = 0; i < count; i++) {
ncount = 1;
for(j = i + 1; j < count; j++) {
/*Part to perform checking for duplicate elements*/
if(arr[i] == arr[j]) {
ncount++;
/*Make sure not to count frequency of same element again*/
Freq[j] = 0;
}
}
/*If frequency of current element is not counted*/
if(Freq[i] != 0) {
Freq[i] = ncount;
}
}
printf(" ELEMENT | FREQUENCY \n");
printf("-------------------------\n");
for (i = 0; i < count; i++) {
if(Freq[i] != 0) {
printf("\t%d\t\t\t%d\n", arr[i], Freq[i]);
}
}
}
Also, from your code:
You did not define i and n, which is required by your for loop. Also, since your for loop is for (i = 0; i<=n; i++), you have to define the value of n, which is the length of elements inputted by the user, in order to loop through the number of elements you expected.
int i, n, num;
...
...
for (i = 0; i<=num; i++)
Your scanf("i%", &num); should be scanf("%i", &num); instead.
You did not initialize your array a. You should have this line of code before assigning values to your array a. The value 20 can be adjusted by yourself depending on how many inputs are expected. Also, it can be coded in a flexible way instead of hardcoded as 20.
...
int i, num;
int count=0;
int a[20];
...
...
Lastly, it is a good practice to include the function's library before using it. In your case, you should include #include <conio.h> to use the getch() function.
trying to read in from a text file with 10 lines of 10 numbers separated by spaces. I want to directly save each number into a space in the matrix numList.
Really not sure what the problem is with my code, I think it might be because i'm not initializing the matrix correctly or something. Any help appreciated
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
FILE* fpointer = fopen("numbers.txt", "r");
if (fpointer == NULL) {
printf("No file found");
return 1;
}
// INITIALISE MATRIX
char* numList[10][10];
char buffer[300];
// COPY NUMBERS INTO MATRIX
int i = 0;
while (fgets(buffer, 300, fpointer)) {
int j = 0;
char* p = strtok(buffer, " ");
while ((p != NULL)&&(j<10)) {
printf(" %s ",p);
strcpy(numList[i][j],p);
p = strtok(NULL, " ");
j++;
}
printf("\n");
i++;
}
printf("\n\n");
//Print Final Matrix
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
printf("%s ", numList[i][j]);
}
printf("\n");
}
fclose(fpointer);
return 0;
}
Problem is occurring on the strcpy(numList[i][j],p) function but i'm not sure why.
Output: Exception thrown at 0x7C15EE87 (ucrtbased.dll) in asd.exe: 0xC0000005: Access violation writing location 0xCCCCCCCC.
No memory is allocated for numList[i][j]
You can use strdup instead of strcpy
while (fgets(buffer, 300, fpointer)) {
int j = 0;
char* p = strtok(buffer, " ");
while ((p != NULL)&&(j<10)) {
printf(" %s ",p);
numList[i][j] = strdup(p);
p = strtok(NULL, " ");
j++;
}
printf("\n");
i++;
}
I am very confused to create a function which will print a string and ask user to enter two numbers and then function will replace those number of words with one another.
I have added the image below as sample.
enter image description here
This is my homework, I have created other 3 functions, but don't really get this one.
Could somebody please help me how can I convert the words into numbers and then replace those number of words with one another.
This is my program it can break the string into words but how can i replace position of words.
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100];
char newString[10][10];
int i,j,ctr;
printf("\n\n Split string by space into words :\n");
printf("---------------------------------------\n");
printf(" Input a string : ");
fgets(str1, sizeof str1, stdin);
j=0; ctr=0;
for(i=0;i<=(strlen(str1));i++)
{
// if space or NULL found, assign NULL into newString[ctr]
if(str1[i]==' '||str1[i]=='\0')
{
newString[ctr][j]='\0';
ctr++; //for next word
j=0; //for next word, init index to 0
}
else
{
newString[ctr][j]=str1[i];
j++;
}
}
printf("\n Strings or words after split by space are :\n");
for(i=0;i < ctr;i++)
printf(" %s\n",newString[i]);
return 0;
}
Seems to me that you are doing pretty good so far (your code can't handle comma but you can add that later). So let's assume that your newString actually contains the individual words.
So your next step is to construct a new string str2 from the individual words you have in newString. While you do that you can simply swap the two words of interest. To build the new string the strcat function could be helpful.
The code below is not fully correct but it may give you some ideas for getting on with your homework:
int lowest_index_to_swap = some_number
int highest_index_to_swap = some_higher_number
char str2[100] = "";
for (i=0; i<number_of_words_found; ++i)
{
if (i == lowest_index_to_swap)
strcat(str2, newString[highest_index_to_swap];
else if (i == highest_index_to_swap)
strcat(str2, newString[lowest_index_to_swap];
else
strcat(str2, newString[i];
strcat(str2, " ";
}
Here is code snippet what I tried in my local server based on your input in image.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SIZE 100
#define WORDLEN 20
int main() {
int place_1, place_2, count = 0, i, k =0;
char str[] = "Hi, welcome to C programming";
char **words = (char **)malloc(sizeof(char *)*SIZE);
if(!words){
printf("malloc of words failed!\n");
exit(1);
}
char *temp = (char *)malloc(sizeof(char)*WORDLEN);
if(!temp){
printf("malloc of temp failed!\n");
exit(1);
}
for(i = 0; str[i] != '\0'; count++){
words[count] = (char *)malloc(sizeof(char)*WORDLEN);
if(!words[count]){
printf("malloc of words[%d] failed!\n", count);
exit(1);
}
sscanf(str+i, "%s", words[count]);
i += 1+strlen(words[count]);
printf("%d %s %d\n", count, words[count], i);
}
printf("Enter the word places to replace: ");
if(scanf("%d %d", &place_1, &place_2) < 2){
printf("scanf failed!\n");
exit(1);
}
temp = words[place_1 - 1];
words[place_1 - 1] = words[place_2 - 1];
words[place_2 - 1] = temp;
for(i = 0; i < count; i++){
sprintf(str+k, "%s ", words[i]);
k += 1+strlen(words[i]);
}
printf("str: %s\n", str);
free(temp);
for(i = 0; i < count; i++){
free(words[i]);
}
free(words);
}
Hope it helps.