How to add if-else statement for "kodeprodi"?
Everytime I add if-else statement, the message "Lvalue required" always appears.
#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
typedef struct {
char bp[13];
char nama[15];
int kodeprodi;
char namaprodi[10];
float ipk;
} mahasiswa;
int main()
{
char pil;
do {
mahasiswa mhs[10];
int i, n;
{
printf("Data Nilai Mahasiswa\n");
printf("Berapa banyak data = ");
scanf("%d", &n);
for(i = 0; i < n; i++) {
printf("Data mahasiswa ke-%d\n", i+1);
printf("Nomor BP: "); scanf("%s", &mhs[i].bp);
printf("Nama: "); scanf("%s", &mhs[i].nama);
printf("Kode Prodi: "); scanf("%d", &mhs[i].kodeprodi);
printf("IPK: "); scanf("%f", &mhs[i].ipk);
if (mhs[i].kodeprodi == 260) {mhs[i].namaprodi = "SI";}
else if (mhs[i].kodeprodi == 261) {mhs[i].namaprodi = "TI";}
}
//output
printf("No. BP Nama Kode Prodi Nama Prodi IPK \n");
for(i = 0; i < n; i++) {
printf("\n%2d %-10s %-9s %3d %3s %3.f\n",
i+1, mhs[i].bp, mhs[i].nama, mhs[i].nama,
mhs[i].kodeprodi, mhs[i].namaprodi, mhs[i].ipk);
}
}
printf("Repeat again? Y/N");
scanf("%s", &pil);
printf("\n\n");
} while ((pil == 'Y') || (pil == 'y'));
}
Even if in the statement if-else, I type like this
if(mhs[i].kodeprodi==260){namaprodi = "SI");
The error message is "Undefined symbol 'namaprodi'
I tweaked your code a bit. Got rid of unused conio.h, changed kodeprodi type to int (because char can only handle numbers -127..127), removed & from some scanf calls (because you should pass pointer to first character for %s formatter), deleted extra mhs[i].nama argument for printf.
Sorry, I completely didn't understood your code :-) My tweaks were semi-automatic! You should learn C programming better.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char bp[13];
char nama[15];
int kodeprodi;
char namaprodi[10];
float ipk;
} mahasiswa;
int main() {
char pil;
do {
mahasiswa mhs[10];
int i, n;
{
printf("Data Nilai Mahasiswa\n");
printf("Berapa banyak data = ");
scanf("%d", &n);
for(i=0;i<n;i++) {
printf("Data mahasiswa ke-%d\n", i+1);
printf("Nomor BP: "); scanf("%s", mhs[i].bp);
printf("Nama: "); scanf("%s", mhs[i].nama);
printf("Kode Prodi: "); scanf("%d", &mhs[i].kodeprodi);
printf("IPK: "); scanf("%f", &mhs[i].ipk);
if(mhs[i].kodeprodi==260)
strcpy(mhs[i].namaprodi, "SI");
else if(mhs[i].kodeprodi==261)
strcpy(mhs[i].namaprodi, "TI");
}
//output
printf("No. BP Nama Kode Prodi Nama Prodi IPK \n");
for(i=0;i<n;i++) {
printf("\n%2d %-10s %-9s %3d %3s %3.f\n", i+1, mhs[i].bp, mhs[i].nama, mhs[i].kodeprodi, mhs[i].namaprodi, mhs[i].ipk);
}
}
printf("Repeat again? Y/N");
scanf("%s", &pil);
printf("\n\n");
} while ((pil == 'Y') || (pil == 'y'));
return 0;
}
For a quick fix, use:
if(mhs[i].kodeprodi==260){strncpy(mhs[i].namaprodi, "SI", 9);
strncpy() is needed to copy the contents into namaprodi.
namaprodi is a member of struct mahasiswa, so you can't access it directly.
But better use std::string instead.
Also, as #BoPersson mentioned, char kodeprodi; can't hold 260, so you'll better to convert that to an int.
Related
Is there any way to hide user input when asked for in C?
For example:
char *str = malloc(sizeof(char *));
printf("Enter something: ");
scanf("%s", str);getchar();
printf("\nYou entered: %s", str);
// This program would show you what you were writing something as you wrote it.
// Is there any way to stop that?
Another thing, is how can you only allow certain characters?
For example:
char c;
printf("Yes or No? (y/n): ");
scanf("%c", &c);getchar();
printf("\nYou entered: %c", c);
// No matter what the user inputs, it will show up, can you restrict that only
// showing up if y or n are entered?
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <errno.h>
#define ECHOFLAGS (ECHO | ECHOE | ECHOK | ECHONL)
int set_disp_mode(int fd,int option)
{
int err;
struct termios term;
if(tcgetattr(fd,&term)==-1){
perror("Cannot get the attribution of the terminal");
return 1;
}
if(option)
term.c_lflag|=ECHOFLAGS;
else
term.c_lflag &=~ECHOFLAGS;
err=tcsetattr(fd,TCSAFLUSH,&term);
if(err==-1 && err==EINTR){
perror("Cannot set the attribution of the terminal");
return 1;
}
return 0;
}
int getpasswd(char* passwd, int size)
{
int c;
int n = 0;
printf("Please Input password:");
do{
c=getchar();
if (c != '\n'||c!='\r'){
passwd[n++] = c;
}
}while(c != '\n' && c !='\r' && n < (size - 1));
passwd[n] = '\0';
return n;
}
int main()
{
char *p,passwd[20],name[20];
printf("Please Input name:");
scanf("%s",name);
getchar();
set_disp_mode(STDIN_FILENO,0);
getpasswd(passwd, sizeof(passwd));
p=passwd;
while(*p!='\n')
p++;
*p='\0';
printf("\nYour name is: %s",name);
printf("\nYour passwd is: %s\n", passwd);
printf("Press any key continue ...\n");
set_disp_mode(STDIN_FILENO,1);
getchar();
return 0;
}
for linux
For the sake of completeness: There is no way to do this in C. (That is, standard, plain C without any platform-specific libraries or extensions.)
You did not state why you wanted to do this (or on what platform), so it's hard to make relevant suggestions. You could try a console UI library or a GUI library. You could also try your platform's console libraries. (Windows, Linux)
I've been having a few problems with using an array of structs and simply listing them and adding to them. I am not really all too sure about what's happening, I've had a search around and asked a few friends and they've suggested that it is something to do with the memory allocation and another has said that memory allocation is not needed and that there is a problem in my code.
I have been unable to locate the problem and was wondering if anyone would be able to point me in the direction of to where I am going wrong.
I apologies if the code doesn't look right - not really sure on how to implement it on the site.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct data{
int testone;
int testtwo;
}data;
struct data _dataStore[25];
int dataCount = 0;
int addData(struct data __dataStore[dataCount]){
printf("\n\t\t\tPacket Source - ");
scanf("%i", &_dataStore[dataCount].testone);
printf("\t\t\tPacket Destination - ");
scanf("%i", &_dataStore[dataCount].testtwo);
system("CLS");
return 0;
}
void listData(struct data _dataStore[25]){
int i = 0;
for (i = 0; i < dataCount; i++){
printf("data stored - %i",dataCount);
printf("%i___%i \n", _dataStore[dataCount].testone,_dataStore[dataCount].testtwo);
}
}
int main(){
char choice;
do{
printf("\t\t\t Counter - %i", dataCount+1);
printf("\n\t\t\t1 - Add data. \n");
printf("\t\t\t2 - List data. \n");
printf("\n\t\t\tEnter your choice - ");
fflush(stdin);
choice = getchar();
getchar();
switch(choice){
case '1':
addData(&_dataStore[dataCount]);
dataCount++;
system("CLS");
break;
case '2':
system("CLS");
listData(&_dataStore[dataCount]);
break;
default:
printf("Invalid input \n");
break;
}
}while (choice != '5');
return 0;
}
There are quite a few apparent bugs, for example:
for (i = 0; i < dataCount; i++){
printf("data stored - %i",dataCount);
printf("%i___%i \n", _dataStore[dataCount].testone,_dataStore[dataCount].testtwo);
}
}
I suspect you wanted to say _dataStore[i] instead. Also, I suggest using a more sensible function prototype:
int addData(struct data* __dataStore, int arrayLen)
Here is the corrected code which works well for me:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct data{
int testone;
int testtwo;
}data;
struct data _dataStore[25];
int dataCount = 0;
int addData(){
printf("\n\t\t\tPacket Source - ");
scanf("%d", &_dataStore[dataCount].testone);
printf("\t\t\tPacket Destination - ");
scanf("%d", &_dataStore[dataCount].testtwo);
system("CLS");
return 0;
}
void listData(){
int i = 0;
for (i = 0; i < dataCount; i++){
printf("data stored - %d: ",dataCount);
printf("%d___%d \n", _dataStore[i].testone,_dataStore[i].testtwo);
}
}
int main()
{
char choice;
do{
printf("\t\t\t Counter - %i", dataCount+1);
printf("\n\t\t\t1 - Add data. \n");
printf("\t\t\t2 - List data. \n");
printf("\n\t\t\tEnter your choice - ");
fflush(stdin);
choice = getchar();
getchar();
switch(choice){
case '1':
addData();
dataCount++;
system("CLS");
break;
case '2':
system("CLS");
listData();
break;
case '5':
printf("Will exit...");
break;
default:
printf("Invalid input \n");
break;
}
}while (choice != '5');
return 0;
}
Please pay attention to the following: read / write integers with %d not %i, the index in listData() shall be i not dataCount, I removed the not-needed params of the functions since the variables are global, I added a new case in switch() so that it prints a better message when exiting, not "invalid input".
All variables you are using are statically allocated so you do not need memory allocation.
I need to extract a series of information from multiple files (64 files) in a directory. Each file consists of several lines like:
Pair of Operators: 0& ins: 0& rmv: 0& weight: 0.124354
Pair of Operators: 1& ins: 1& rmv: 0& weight: 0.00672458
Pair of Operators: 2& ins: 2& rmv: 0& weight: 0.000467531
...
The information is stored in a vector. I wrote a code, however, I receive a segmentation fault error. Here is my code. Could anyone indicate where the problem comes from?
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string.h>
#include <vector>
#include <dirent.h>
using namespace std;
struct info {
char* name;
vector<vector<double>> weights; // dest-const-weight
};
int main(int c, char* v[]) {
struct dirent* pDirent;
DIR* pDir;
char buffer[50];
strcpy(buffer, v[1]);
if (c < 2) {
printf ("Usage: testprog <dirname>\n");
return 1;
}
pDir = opendir (buffer);
if (pDir == NULL) {
printf ("Cannot open directory '%s'\n", v[1]);
return 1;
}
vector<info> Information;
for (int inst = 0; inst < 64; inst++) {
info temp;
temp.weights.resize(9);
for (int j = 0; j < 9; j++)
temp.weights[j].resize(4);
Information.push_back(temp);
}
int cmp = 0;
while ((pDirent = readdir(pDir)) != NULL) {
if (strcmp(pDirent->d_name, ".") != 0 &&
strcmp(pDirent->d_name, "..") != 0) {
char line[1024];
ifstream file(pDirent->d_name);
Information[cmp].name = pDirent->d_name;
int oper = -1;
int dest = -1;
int ins = -1;
double weight = -1;
for (int l = 0; l < 36; l++) {
file.getline(line, 1024);
// cout<<line<<endl;
sscanf(line,
"Pair of Operators: %d& ins: %d& rmv: %d& weight: %f",
&oper, &dest, &ins, &weight);
// sscanf(line, "%*s %d%*s %d%*s %d%*S %f", &oper, &dest, &ins,
// &weight);
// cout<<oper<<" "<<dest<<" "<<ins<<" "<<weight<<endl;
Information[cmp].weights[dest][ins] = weight;
}
cmp++;
}
}
closedir(pDir);
return 0;
}
I can see two obvious seg faults.
First of all you copy v[1] into buffer. Do you provide any arguments to your program?
Second one I see on the fly is that you try to call readdir on a uninitialized pointer of DIR.
Try DIR* pDir = opendir(...);
You should always print a usage message when the argument count doesnt match!
if (c != 1) {
fprintf(stderr, "USAGE: %s needs exactly one argument!\n" v[0]);
return 0;
}
One more thing I forgot to mention. You can compile your program with the -g flag and try to use a debugger to find these errors.
the issue is in the read_in function when i use fgets to read in the users input for a band/singer it will just skip this line. I cant work out why this is happening? I did use scanf for this before but the issue is that if you do that when you enter a band name with a space e.g 'foo fighters' it will skip the next print name of reference line. Anyone know how to fix this?
#include <stdio.h>
#include <conio.h>
#define MAX 1000`enter code here`
int exit = 0; // Declaring a global variable
struct data { // using struct to put the data in an arrays
char band [48], cd [48], ref [16];
float cost;
int year;
} cata [MAX]; // declaring a struct variable
int read_in ( void )
{
int i = 0;
printf("\n");
while ( exit != 2 ) // while exit != 2 then ask the user to enter the information
{
printf("\nPlease Enter the Name of Band/Singer: ");
fgets(cata[i].band, 48, stdin);
printf("\nPlease Enter the Name of CD: ");
scanf("%s", &cata[i].cd);
printf("\nPlease Enter the Name of the Reference: ");
scanf("%s", &cata[i].ref);
printf("\nPlease Enter the cost: ");
scanf("%f", &cata[i].cost);
printf("\nPlease Enter the Year of Release: ");
scanf("%d", &cata[i].year);
printf("\nWrite another CD: [1] \nMain Menu: [2]\nYour choice: "); // Asking him a choice either write another one or go back to menu
scanf("%d", &exit);
i++;
}
exit = 0;
return i;
}
void print_out (void)
{
FILE *file_cata;
int i = 0;
printf("\n");
while ( exit != 2 )
{
file_cata = fopen ("catalogue.txt", "r"); // open the file and read
if (file_cata == NULL)
{
printf("Error: can't open files.\n");
}
else
{
while (!feof (file_cata))
{
fgets(cata[i].band, MAX , file_cata); // it will scanf the file and get the string and then print it out on screen
printf("%s", cata[i].band);
fgets(cata[i].cd, MAX, file_cata);
printf("%s", cata[i].cd);
fgets(cata[i].ref, MAX, file_cata);
printf("%s", cata[i].ref);
fscanf(file_cata, "%.2f" , cata[i].cost);
fscanf(file_cata, "%d", cata[i].year);
i++;
}
}
fclose (file_cata); // close file
printf("Read it again: [1] \nMain Menu: [2]\nYour choice: ");
scanf("%d", &exit);
}
exit = 0;
}
void save ( int num )
{
FILE *file_cata;
int i = 0;
printf("\n");
while ( exit != 2 )
{
file_cata = fopen ("catalogue.txt", "a"); // file append, so it will write at the end of the file
if (file_cata == NULL)
{
printf("Error: can't open files. \n");
}
else
{
while (i != num)
{
fprintf( file_cata, "\n");
fprintf( file_cata, "The name of Band/Singer: %s \n", cata[i].band);
fprintf( file_cata, "The name of CD: %s \n", cata[i].cd);
fprintf( file_cata, "The name of Reference: %s\n", cata[i].ref);
fprintf( file_cata, "The Cost: %.2f \n", cata[i].cost);
fprintf( file_cata, "The Year of Release: %d \n", cata[i].year);
i++;
}
}
fprintf( file_cata, "\n");
fclose (file_cata);
printf("Your data has been saved to the catalogue.\n\n");
printf("Save it again: [1] \nMain Menu: [2]\nYour Choice: ");
scanf("%d", &exit);
}
exit = 0;
}
void main ()
{
int num1 = 0;
int option = 0;
while ( option != 4 )
{
printf("The following options are availlable: \n");
printf("Read in data [1] \n");
printf("Print out catalogue to screen [2] \n");
printf("Save data to file [3] \n");
printf("Exit Program [4] \n");
printf("Enter your choice now: ");
scanf( "%d", &option);
if (option == 1)
num1 = read_in ();
if (option == 2)
print_out ();
if (option == 3)
save(num1);
printf("\n");
}
printf("\n*** Your program will end when you press ANY button. ***\n");
_getch();
}
The scanf is leaving the newline in the input buffer. Related question with a very good answer (Hint: don't use scanf; use fgets always, plus sscanf if you must convert that way.): Replacement of fflush(stdin)
This flushes the input buffer, which you should do before attempting to read another line (stolen from answer above):
while((c = getchar()) != '\n' && c != EOF)
So I'm getting this error when i compile my code (expected ‘,’ or ‘;’ before ‘{’ token {) I know there may be many of these errors out there on stackoverflow, but can't seem to find a solution:
I'm new to c++. Here is the code: I have to read data from a text file (data.txt) and display it:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main(){
FILE *fptr;
char country[5][20];
int population[5];
int landMass[5];
int option;
int i;
int countryOption;
int gdp[5];
int populationDensity[5];
int gdpHead[5];
//open file for reading
fptr = fopen("data.txt", "r");
//Error checking
if (fptr == NULL) {
printf("Unable to open data.txt");
return(1);
}
//input from user
printf("Hi welome to the country database!");
getchar();
system("cls");
printf("Select a country for information:\n");
printf("1)Canada\n");
printf("2)Italy\n");
printf("3)China\n");
printf("4)USA\n");
printf("5)Russia\n");
printf("6)All\n");
printf("Type in the option you want:");
scanf("%d", &option);
system("cls");
//reads data from data.txt and assigns to variables
for (i = 1; i <= 5; i++) {
fscanf(fptr, "%s %d %d %d", country[i], &population[i], &landMass[i], &gdp[i]);
populationDensity[i] = (population[i]/landMass[i]);
gdpHead[i] = ((gdp[i]*1000000)/population[i]);
if (option == 6) {
printf("Here is info on all the countries in our database:\n");
printf("Country: %s\n", country[i]);
printf("Population: %d\n", population[i]);
printf("LandMass: %d\n", landMass[i]);
printf("GDP: %d\n", gdp[i]);
printf("Population density: %d\n", populationDensity[i]);
printf("Population density: %d\n\n\n", gdpHead[i]);
}
}
void countrySelection(int countryOption)
{
printf("Here is some info on the country you chose:\n");
printf("Country: %s\n", country[countryOption]);
printf("Population: %d\n", population[countryOption]);
printf("LandMass: %d\n", landMass[countryOption]);
printf("GDP: %d\n", gdp[countryOption]);
printf("Population density: %d\n", populationDensity[countryOption]);
printf("Population density: %d\n\n", gdpHead[countryOption]);
}
//function that prints the info
if (option < 6) {
countrySelection(option);
}
fclose(fptr);
system("pause");
return(0);
}
The data.txt looks like this:
Canada
42000000
9984670
1821000
Italy
60920000
301230
2013000
China
1351000000
9706961
8227000
USA
313900000
9826675
15680000
Russia
143000000
17098246
2015000
Any one have a clue as to what the problem is???
You are defining void countrySelection(int countryOption) inside the main function, which is not allowed in c++.
Move the function above the main function and it should compile.
Also you have to define the variables used in countrySelection as global variables, otherwise the function has no access to them.