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++;
}
Related
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.
I tried to read a file containing an empty box of '*', the error message doesn't get printed, so the file is opened, but the scan doesn't work. I tried to print the count variable, and the value of count is 0. I don't really know where the fault is. Please help... Thanks
the file content that I want to read
int openmap(int file_no){
char filename[32];
char mapp[100][100];
int number;
int count;
int x[100];
int nomor = 1;
for(int i = 1; i <= file_no; i++){
sprintf(filename, "map%d.txt", i);
FILE *test = fopen(filename,"r");
if(test)
{
printf("%2d. Map %d\n", nomor, i);
x[nomor-1] = i;
nomor++;
fclose(test);
}else if(!test && i > file_no){
printf("No map available!");
return 1;
}
}
do{
printf("[0 to cancel] [1 - %d]>> ", nomor-1);
scanf("%d", &number);
}while(number < 0 || number > file_no);
if(number > 0){
sprintf(filename,"map%d.txt", x[number-1]);
printf("%s", filename);
FILE *open = fopen(filename, "r");
if(!open){
printf("error");
}
while(!feof){
fscanf(open, "%[^\n]\n", mapp[count]);
count++;
}
fclose(open);
for(int i = 0; i < count ; i++){
printf("%s\n", mapp[i]);
}
}
}
I created a small test program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main () {
char mapp[100][100];
int i, count = 0;
char filename[32];
sprintf(filename, "test.txt");
FILE *open = fopen(filename, "r");
if(!open){
printf("error");
}
while(!feof(open)){
fscanf(open, "%[^\n]\n", mapp[count]);
count++;
}
fclose(open);
for(i = 0; i < count ; i++){
printf("%s\n", mapp[i]);
}
}
as far as i can see the only issue you have regarding the relevant section is your while loop condition, you should use: while(!feof(open)) - i tested my solution and it works so it seems that this is the only issue in your solution
Here is my code so far. I am perfectly able to sort files holding numbers but clueless when it comes to characters. It takes in a file of my choosing and outputs another file with the sorted array. But so far all I'm getting are blank files and I can't figure out why.
So how can I fix my code to sort an array of characters and then output it?
#include <stdio.h>
int bubble_sort(char *a, int n);
int main(void) {
char a[10];
int n = sizeof a / sizeof a[10];
int i;
char inname;
char outname;
printf("Enter input name: ");
scanf("%s", &inname);
printf("Enter output name: ");
scanf("%s", &outname);
FILE *in, *out;
out = fopen(&outname, "w");
if ((in = fopen(&inname, "r")) == NULL) {
printf("File not found\n");
}
else {
for (int i = 0; i < 10; i++)
{
fscanf(in, "%s ", &a[i]);
}
bubble_sort(a, n);
for (i = 0; i < 10; i++) {
printf("%s\n", a[i]);
fprintf(out, "%s\n", a[i]);
}
}
fclose(in);
fclose(out);
return 0;
}
int bubble_sort(char *a, int n) {
int i, j;
char temp;
for (j = 1; j<n; j++)
{
for (i = 0; i<n - j; i++)
{
if ((int)a[i] >= (int)a[i + 1])
{
temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
}
}
return a[i];
}
The basic problem, as I can see, is with
scanf("%s", &inname);
In your code, inname is a single char, which cannot hold string inputs. You'll be needing an array.
You need to change
char inname;
char outname;
to
#define NAMSIZ 32
char inname[NAMSIZ] = {0};
char outname[NAMSIZ] = {0};
and then,
scanf("%31s", inname);
and accordingly.
Same problem exist with fscanf(in, "%s ", &a[i]);, too.
I am trying to read a txt file and then split the numbers and store them in a matrix. However when I try to use strtok I'm getting segmentation fault. Can somebody help me with this pleaseļ¼
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
void parse(char*file1)
{
FILE *fp;
char str[60];
char str1[60];
fp = fopen(file1, "r");
int row;
int col;
fgets(str, 60, fp);
row=atof(str);
fgets(str, 60, fp);
col=atof(str);
double *matrix;
matrix = (double *)malloc(sizeof(double)*row*col);
int j;
int i;
for(i=0; i < row; i++) {
for(j=0; j < col; j++) {
matrix[i*col +j] = 1;
}
}
for(i=0; i < row; i++) {
for(j=0; j < col; j++) {
printf("%f ",matrix[i*col +j]);
}
printf("\n");
}
printf("**************************");
double dtoken;
while (!feof(fp))
{
if (fgets(str, 60, fp)==NULL)
{
break;
}
else
{
char*token;
token = strtok(str, " ");
while (token!=NULL)
{
printf("%s ",token);
token=strtok(NULL, " ");
}
}
printf("\n");
}
fclose(fp);
}
int main(int argc, char*argv[])
{
int i;
char*file1;
char*file2;
if (argc==1) //print error when no txt file is entered
{
printf("Invalid text file.\n");
exit(1);
}
else if (argc==2)
{
file1=argv[1];
file2=argv[1];
}
else if (argc==3)
{
file1=argv[1];
file2=argv[2];
}
else
{
exit(1);//more than 3 files, invalid
}
//
parse(file1);
}
I tried copying str to str1 and use strtok on str1 and that did not work either.
In the function parse() change str1[60]='\0'; to str1[59]='\0';
As you have allocated memory only for 60 characters and trying to access the 61st character.
In arrays you need to count from 0 to 59 and not from 1 to 60 if the size of allocated array is 60.
EDIT:
Check for the return value of fopen
After fp = fopen(file1, "r"); add below code
if (fp == NULL ) {
printf("Error: Unable to open file\n");
return ;
}
You are causing undefined behavior by accessing str1 out of bounds. You can replace the lines:
strncpy(str1,str,60);
str1[60]='\0';
by
strcpy(str1,str);
That will work fine since both str and str1 are arrays with 60 elements.
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++;
}