How to remove the spaces and newline when writing in file? [duplicate] - c

This question already has answers here:
Removing trailing newline character from fgets() input
(14 answers)
Closed 2 years ago.
The code is working fine but whenever I type the words second time and it comes to seeing the result in a file, it gives me the result like this. How to handle this?
Name, DOB, ID, Phone
Name
, DOB, ID, Phone
The Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 50
int main(){
FILE * fw = fopen("new.csv", "a");
char* listing[] = {"Name", "Date of birth","ID card number","Phone number"};
char data[4][LEN], name[LEN], amount[LEN], dob[LEN], id[LEN], option;
int i, done=0;
do{
for (i = 0; i < 4; i++) {
printf("Enter your %s: ", listing[i]);
fgets(data[i], LEN, stdin);
if(strcmp(data[i], "\n") == 0){
fgets(data[i], LEN, stdin);
}
else{
data[i][strlen(data[i])-1] = '\0';
}
}
fprintf(fw, "%s, %s, %s, %s\n", data[0], data[1], data[2], data[3]);
printf("Do you want to continue [y/n]: ");
scanf("%s", &option);
}
while(option == 'y');
fclose(fw);
return 0;
}

Try this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 50
int main() {
FILE * fw = fopen("new.csv", "a");
char * listing[] = {
"Name",
"Date of birth",
"ID card number",
"Phone number"
};
char data[4][LEN], name[LEN], amount[LEN], dob[LEN], id[LEN], option;
int i, done = 0;
do {
for (i = 0; i < 4; i++) {
printf("Enter your %s: ", listing[i]);
fgets(data[i], LEN, stdin);
while (strcmp(data[i], "\n") == 0) { //<------Changed if condition to while loop
fgets(data[i], LEN, stdin);
}
data[i][strlen(data[i]) - 1] = '\0';
}
fprintf(fw, "%s, %s, %s, %s\n", data[0], data[1], data[2], data[3]);
printf("Do you want to continue [y/n]: ");
scanf("%s", & option);
}
while (option == 'y');
fclose(fw);
return 0;
}
I changed the if statement to while loop where you checked if input is '\n'.

Related

C language - printing some sentences to file

I want to read strings and write them as full lines into a file, but I can't read more words into a buffer as a complete string.
Current problematic code:
printf("\nEnter how many sentences do you want to read: ");
scanf("%d", &n);
tab = (char**)malloc(n * sizeof(char*));
for (int i = 0; i < n; i++) {
printf("\nEnter sentence: ");
scanf("%s", val);
tab[i] = _strdup(val);
}
for (i = 0; i < n; i++)
fprintf(f, "%s ", tab[i]);
free(tab);
Previously I tried this: (problem is this only assigns one string)
printf("\nEnter how many sentences do you want to read: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("\nEnter sentence: ");
scanf("%s", val);
fprintf(f, "\%s ", val);
}
Almost there, now i have sentences but i got one empty line as first line of file.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string>
#define SIZE 30
void creare(char t[30]);
void main(void)
{
FILE* f2;
char name[30];
printf("\nEnter name of file to work with: ");
scanf("%s", name);
creare(name);
f2 = fopen(name, "r");
if (f2 == NULL)
{
printf("\nOpen error!!");
exit(0);
}
fclose(f2);
printf("\n");
_getch();
}
void creare(char t[30])
{
FILE* f;
int n,i;
char val[30];
f = fopen(t, "w");
if (f == NULL)
{
printf("\nOpen error!!");
exit(0);
}
printf("\nEnter how many sentences do you want to read: ");
scanf("%d", &n);
for (i = 0; i <= n; i++)
{
fgets(val, sizeof(val), stdin);
fprintf(f, "% s", val);
}
fclose(f);
}
I have used fgets(val, sizeof val, stdin) to read the string, because to read string with spaces.
The reason why that blank line comes in file is due to the fact that you are reading "\n" that is inputted after scanf("%d", &n);The keystroke "\n" will be read into val for the first time so it simply prints that "\n" to the file.
In order to read that "\n" use a character to read that "\n". Below is the complete program.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#define SIZE 30
void creare(char t[30]);
int main(void)
{
FILE* f2;
char name[30];
printf("\nEnter name of file to work with: ");
scanf("%s", name);
creare(name);
f2 = fopen(name, "r");
if (f2 == NULL)
{
printf("\nOpen error!!");
exit(0);
}
fclose(f2);
printf("\n");
}
void creare(char t[30])
{
FILE* f;
int n,i;
char val[30],g;
f = fopen(t, "w");
if (f == NULL)
{
printf("\nOpen error!!");
exit(0);
}
printf("\nEnter how many sentences do you want to read: ");
scanf("%d", &n);
scanf("%c",&g);
for (i = 0; i <n; i++)
{
fgets(val, sizeof(val), stdin);
fprintf(f, "%s", val);
}
fclose(f);
}

while using fgets and printf in C, it appears "00“ in the screen, do you know why and where "00" comes from?

I want print every line of one file, and I also want divide each line into several parts in a array and then use atoi() to change the string into int, but eventually I get a wired 00 in the end, I don't know where it comes from, can anybody help?
#include <stdio.h>
#include <stdlib.h>
#include "tabu.h"
#include <stdbool.h>
#include <string.h>
int main(int argc, const char *argv[]) {
int city[30][30];
FILE *fp = fopen("/Users/wuchangli/Desktop/Cpractice/tabu_6010/tabu_6010_/tabu_6010_/30.in", "r");
if (fp == NULL) {
printf("error");
}
char data[20];
int n = 0;
char *token;
int ct[3];
int mm = 0;
while (fgets(data, 30, fp) != NULL) {
//fflush(stdin);
//fflush(stdout);
//fflush(stdin);
//fflush(stdout);
//printf("\n%s\n", data);
printf("\n%s\n", data);
token = strtok(data, " ");
while (token != NULL && n > 0) {
printf("%s\n", token);
ct[mm] = atoi(token);
printf("%d\n", ct[mm]);
token = strtok(NULL, " ");
mm++;
}
city[ct[0]][ct[1]] = ct[2];
printf("%d", city[ct[0]][ct[1]]);
city[ct[1]][ct[0]] = ct[2];
printf("%d", city[ct[1]][ct[0]]);
n++;
}
//for (int ii = 0; ii < 30; ii++) {
// for (int jj = 0; jj < 30; jj++) {
// printf("%d%d is %d\n", ii, jj, city[ii][jj]);
// }
//}
fclose(fp);
return 0;
}
here is the link of my files:enter link description here
You have two issues :-
in this part you are continuously increasing the mm++ but not initialize the mm again when you are going to read another line from file. issue is array bound error.
while(fgets(data, 30, fp)!=NULL){
printf("data is = %s\n", data);
edited: mm=0;
token=strtok(data, " ");
while(token!=NULL)
{
printf("token is = %s\n", token);
ct[mm]=atoi(token);
printf("%d....%d\n",mm,ct[mm]);
token=strtok(NULL, " ");
mm++;
}
Second issue is :-
you have one arrey city[30][30], where row and column, both are 30.
in you code you reading a file that conation string like "30 435", and performed strtok() operation on each string and saved conversion of string to int in ct[0] = 30 and ct[1] = 435. you got issue because array bound checking.
ct[1] is 435 but you define city[30[30].
city[ct[0]][ct[1]]=ct[2];
printf("%d", city[ct[0]][ct[1]]);
city[ct[1]][ct[0]]=ct[2];
printf("%d", city[ct[1]][ct[0]]);

how to stop a while loop to enter, in the same variable

I have to enter random names and weights and finish the loop when I hit enter instead of the name. However the way I used to detect the enter does not serve to take the name so getting two variables. The question is how to put the enter of the test and name using the same variable
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
int c, weight[1000], i = 0;
char name[1000];
puts ("Enter the person's name or only enter to end the program");
if ((c = getchar() == '\n')) {
} else {
while (c != '\n') {
printf("Enter the name");
scanf("%s", &nome[i]);
i++;
printf("Enter the \n");
scanf("%i", &weight[i]);
}
}
return 0;
}
Here is a simple example
#include <stdio.h>
#include <string.h>
int main(void)
{
char name[1000] = {0}; // initialise
puts ("Enter the person's name or only enter to end the program");
if (fgets(name, sizeof(name), stdin) != NULL) {
name [ strcspn(name, "\r\n") ] = 0; // remove trailing newline etc
if (strlen(name)) {
printf("The name entered was: %s\n", name);
}
else {
printf("You did not enter a name\n");
}
}
return 0;
}
First off, names is an array of characters and you're treating it like an array of strings. Secondly, loops that need to exit based on input are most clearly expressed with break:
char *names[1000];
int count = 0;
while (1) {
char *r, buf[1000];
int len;
char *r = fgets(buf, 1000, stdin);
if (NULL == r) break; // EOF
if ((len = strlen(buf)) < 2) break; // NL only
r = malloc(len + 1);
if (NULL == r) break;
strcpy(r, buf);
names[count] = r;
count += 1;
...
}
...

Search file and compare strings it contains with inputted variable

I'm trying to search a file containing information on a group of people, for example: their first name, last name and ID.
I'm prompting the user to enter their ID code. The program should search the text file and ensure that their code matches the one within the file so that the program can continue by comparing the string from the file and the variable inputted by the user.
I'm not sure how to implement this. Below is a snippet of the code:
#include <stdio.h>
#include <conio.h>
#include <string.h>
typedef struct record {
char (fname[3])[20];
char (lname[3])[20];
int code[3];
} information;
int main (void) {
char ffname[20], flname[20];
int fID, i;
FILE *kfile;
if ((kfile = fopen("C:\\Users\\Student\\Downloads\\information.txt","r")) == NULL) {
perror("Error while opening file");
} else {
printf("%-20s %-20s %s\n", "First Name", "Last Name", "ID");
fscanf(kfile, "%19s %19s %d", ffname, flname, &fID);
printf("\n");
while (!feof(kfile)) {
printf("%-20s %-20s %04d\n", ffname, flname, fID);
fscanf(kfile, "%19s %19s %d", ffname, flname, &fID);
}
fclose(kfile);
}
information info;
for (i = 0; i < 3; i++) {
printf("Please enter your ID.");
scanf("%04d", &info.code);
}
getch();
return 0;
}
I'm not sure I understand your problem, but you can try this:
typedef struct record {
char *fname;
char *lname;
int code;
} information;
int main (void) {
char ffname[28], flname[28];
int fID, i, id_;
information array[3];
FILE *kfile;
i = 0;
if ((kfile = fopen("C:\\Users\\Student\\Downloads\\information.txt","r")) == NULL) {
perror("Error while opening file");
} else {
while (!feof(kfile)) {
fscanf(kfile, "%s %s %d", ffname, flname, &fID);
array[i].fname = strdup(ffname);
array[i].lname = strdup(flname);
array[i].code = fID;
i++;
}
fclose(kfile);
}
printf("Please enter your ID: ");
scanf("%d", &id_);
for (i = 0; i < 3; i++) {
if (array[i].code == id_) {
// print the record
printf("%s %s \n", array[i].fname, array[i].lname);
}
}
return 0;
}

Having problems with my file read, using a struct

I got my struct the right way, and it seems like a lot of this is working. However I got a small problem with my strings reading this garbage in my file read. I am trying to just pull a name, date, and state. And it keeps producing this odd form of "]][]]]][[[[[[" before the actual date, name, or state. How do I get my struct to read the file without getting this garbage feedback.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <cstdio>
#include <iostream>
#include <fstream>
#include <cstring>
#include <exception>
//functions called
void get_info(int id[], char name[][20], char state[][5], char dis_code[], float balance[], char due_date[][40]);
void print_list(int id[], char name[][20], char state[][5], char dis_code[], float balance[], char due_date[][40]);
//why is it void?
int main(void)
{
FILE *pFile;
int choice = 0;
char buf[40];
/*
int id[sizeof(buf)];
char name[sizeof(buf)][20];
char state[sizeof(buf)][5];
char dis_code[sizeof(buf)];
float balance[sizeof(buf)];
char due_date[sizeof(buf)][40];
*/
struct fileinfo
{
int id[40];
char name[40][20];
char state[40][5];
char dis_code[40];
float balance[40];
char due_date[40][40];
} info;
printf("WELCOME. \n");
while (choice != 5)
{
printf("press number for action\n");
printf("OPEN FILE - 1 \n");
printf("LIST THE TABLE - 2 \n");
printf("SEARCH THE TABLE -3 \n");
printf("ADD A NEW ROW - 4 \n");
printf("EXIT THE PROGRAM - 5 \n");
gets_s(buf);
choice = atoi(buf);
if (choice == 1)
{
pFile = fopen("ASSIGNV1.dat", "r");
if (pFile != NULL)
{
int i = 0;
for (i = 0; i < 8; i++)
{
//get id
fgets(buf, sizeof(buf), pFile);
info.id[i] = atoi(buf);
//get name
fgets(buf, sizeof(buf), pFile);
info.name[i][strlen(info.name[i]) - 1] = '\0';
//get state
fgets(buf, sizeof(buf), pFile);
info.state[i][strlen(info.state[i]) - 1] = '\0';
//get discount code
fgets(buf, sizeof(buf), pFile);
info.dis_code[i] = buf[0];
//get balance
fgets(buf, sizeof(buf), pFile);
info.balance[i] = atof(buf);
//get due date
fgets(buf, sizeof(buf), pFile);
info.due_date[i][strlen(info.due_date[i]) - 1] = '\0';
printf("ID \t\t %i \n", info.id[i]);
//problem with name
printf("NAME \t\t %s \n", info.name[i]);
//problem with state
printf("STATE \t\t %s \n", info.state[i]);
printf("DISCOUNT CODE \t %c \n", info.dis_code[i]);
printf("BALANCE \t %.2f \n", info.balance[i]);
//problem with due_date
printf("DUE DATE \t %s \n\n", info.due_date[i]);
}
}
printf("\n\nfile was opened and loaded\n\n");
}
}
printf("\n\n PROGRAM WILL END NOW");
system("pause");
}
My text file is this:
125
LIPSO FACTO
SC
A
118.03
07/12/1998
193
GRADE BIT
OR
A
522.83
03/31/2003
237
MORE MATZOES
TN
846.29
01/11/2011
305
AIR BANGLEDESH
VT
A
3064
01/06/2005
485
FRED'S TATOOS
VT
C
2000.04
09/01/2007
520
WORLD WIDE WICKETS
WI
6280.43
04/29/1999
693
TAMMALIZATION
SC
B
3728
10/06/2009
746
REPLACEMENT PARTS
GA
C
5601.31
06/08/2003
probably you are missing to use strcpy().you have to copy buf to info.name[i] and to info.state[i].
The below 3 statements doesn't make sense as you have not copied the string, but trying to terminate the string. Please copy the string then terminate it
info.name[i][strlen(info.name[i]) - 1] = '\0';
info.state[i][strlen(info.state[i]) - 1] = '\0';
info.due_date[i][strlen(info.due_date[i]) - 1] = '\0';

Resources