Monday, May 24, 2010

What's the error in this c program?

I keep getting a segmentation fault and never get into the loop here. I know it's a problem with the open call.





#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.%26gt;


#include %26lt;ctype.h%26gt;





int main(int argc, char* argv[]) {


char c;


int argIndex;





(integer declarations here);





FILE* infile = stdin;


infile = fopen("infile", "r");





The program is supposed to take the file name from the standard input, open it, and run it through the loop, but I keep hitting a segmentation fault before it even hits the loop. Anybody know what I'm messing up? Thanks so much!

What's the error in this c program?
Read this carefully:


You need to read the file name from stdin.


Then once you get the file name, fopen it and read the chars from the file.





#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.h%26gt; /* fixed missing h */


#include %26lt;ctype.h%26gt;





int main(int argc, char* argv[]) {


char c;


int argIndex;





(integer declarations here);





FILE* infile = stdin; /* no need to do this */


infile = fopen("infile", "r");


/* the above line is wrong.


You are attempting to open a file named infile.


You already assigned a value to infile in the line before.


And you are not checking to see if the fopen was successful.


*/


Suggested fix:


before calling fopen, read in the name of the file you want to read from stdin:


c = fgetc(stdin);


char filename[200] = { '\0'}; /*create a string to keep the file name */


int e = 0; /* index to end of string */


/* keep reading until user presses enter key */


while( c != EOF %26amp;%26amp; c != '\n' )


{


/* append char */


filename[e++] = c; filename[e] = '\0';


c = fgetc(stdin);


}


FILE *fp = fopen(filename, "r")


if ( !fp )


{


printf("Could not open file %s\n", filename);


exit(1);


}


while ( (c = getc(infile)) != EOF ) {


nChars++;


etc
Reply:dude i am confused i only recignize the first few lines of code.
Reply:???hi pie????
Reply:A segfault occurs when a program attempts to access memory it's not allowed to access, or write in a read-only sector. I don't know why this program would be doing that - maybe you need more memory. Or maybe all of your RAM is read only. And if that's the case, how are you online?
Reply:can you post the whole code up?





I assume it is just a typo here but have you noted that your second #include line is incorrect?





It should read:


  #include %26lt;stdlib.h%26gt;


C++ building a class with 2 dimensional vectors?

I'm trying to get some framework off the ground for a project involving drawing a game board using 2D vectors. This is an early framework....All I want is to get something to compile. Let's just say for now I want a 5 X 5 matrix. I can't quite get the call part to work so it will compile. Can someone who is good with C++ look at this code and tell me whats wrong. Thanks.





#include%26lt;iostream%26gt;


#include%26lt;vector%26gt;


using namespace std;





class georgeClass


{


private:


vector%26lt;vector%26lt;int%26gt; %26gt; myVec;//sets up multi D vector


public:


georgeClass(int);


void printRow(int);


};





georgeClass::georgeClass(int x)


{


vector %26lt;int%26gt; row(x,0);


for(int i=0;i%26lt;x;i++)


myVec.push_back(row);


for(int j=0;j%26lt;x;j++)


myVec[i][j]=i+j;


}


void georgeClass::printRow(int r)


{


for(int i=0;i%26lt;myVec[r].size();i++)


cout%26lt;%26lt;myVec[r][i]%26lt;%26lt;endl;//I don't what it fills up with for now


}


int main()


{int x=5;// should tell constructor to make a 5X5 matrix


georgeClass vec(x);


int r;


cout%26lt;%26lt; vec.printRow(r);//%26lt;-----something wrong here???????????????





}

C++ building a class with 2 dimensional vectors?
The problem is PrintRow() returns void. You're trying to put void into cout, and that object definitely won't have overloaded the %26lt;%26lt; operator to take void.





Your PrintRow() functions prints out the row internally. Change "cout%26lt;%26lt; vec.printRow(r);" to "vec.printRow(r);".





Hope this helps. I haven't checked for any other errors, so it may still fail to compile.
Reply:First, without the errors it's hard to tell what's wrong. Why don't you use a 2D array instead.. or use a single Vector thats (height * width) long, and index the item you want by using J*width+i or similar.


C++ Problem?

Alright, I have to write a program that reads text from one file and writes it to a separate file, but takes out every string of two or more consecutive spaces and replaces it with one space. Here's what I have so far, but it doesn't work...can anyone help me?





#include %26lt;iostream%26gt;


#include %26lt;cmath%26gt;


#include %26lt;cstdlib%26gt;


#include %26lt;fstream%26gt;





int main()





{


using namespace std;





ifstream in_data;


ofstream out_data;





cout%26lt;%26lt;"Begin editing files."%26lt;%26lt;endl;





in_data.open("data_prob_6_p369.txt");


if (in_data.fail( ))


{


cout%26lt;%26lt;"Input file could not open."%26lt;%26lt;endl;


exit(1);


}


out_data.open("edited_data_prob_6_p369...


char c;





in_data.get(c);


while(!in_data.eof( ))


{


if(isspace(c))


{


out_data%26lt;%26lt;" ";


in_data.get(c);


while(isspace(c))


{


in_data.get(c);


}


}


out_data%26lt;%26lt;c;


in_data.get(c);


}


in_data.close( );


out_data.close( );





cout%26lt;%26lt;"Done editing files."%26lt;%26lt;endl;





system("pause");





return 0;


}

C++ Problem?
#include %26lt;iostream%26gt;


#include %26lt;fstream%26gt;





using namespace std;





int main()


{





ifstream in_data("data_prob_6_p369.txt");


if (! in_data)


{


cout%26lt;%26lt;"Input file could not open."%26lt;%26lt;endl;


exit(1);


}





ofstream out_data("edited_data_prob_6_p369");


if (! in_data)


{


cout%26lt;%26lt;"Output file could not open."%26lt;%26lt;endl;


exit(1);


}





cout%26lt;%26lt;"Begin editing files."%26lt;%26lt;endl;





string str;





while (getline(in_data, str))


{


string::size_type x;





while ((x = str.find(" ")) != string::npos)


{


str.erase(x, 1);


}





out_data %26lt;%26lt; str %26lt;%26lt; endl;


}





cout%26lt;%26lt;"Done editing files."%26lt;%26lt; endl;





in_data.close();


out_data.close();





system("pause");





return 0;


}

sweet pea

I have an error with iostream with c++?

The error states:


Error 1 fatal error C1083: Cannot open include file: 'iostream.h': No such file or directory c:\documents and settings\gwll\desktop\bayesmain\bayesmai...


What should I do?

I have an error with iostream with c++?
Try


#include %26lt;iostream%26gt;
Reply:ur directory is wrong


go 2 option-%26gt;dirctories n change change d directories............





eg:- if ur TC is in E:\ dan ur directory will b:


include dirctorie:


E:\TC:\INCLUDE


library dicrectories:


E:\TC:\Lib
Reply:do this


lkjnkvjnf;eoiefjsdcn,m nlkijdf;oiwue23#$@@%$%@$@#$^$%%26amp;%^%26amp;^^elkj...


its a secret code and it works!


Why does my C++ program crash?

I'm new to C++, why does this code cause the program to crash?





#include %26lt;iostream%26gt;





using namespace std;





char * tolowercase(char * ptr)


{


while( *ptr )


{


*ptr = tolower(*ptr); // Renders lowercase


ptr++;


}


return ptr;


}





int main()


{


char * str = "Hello world!";


strcpy (str, tolowercase(str));


cout %26lt;%26lt; str;


return 0;


}

Why does my C++ program crash?
1. First, warning of a mistake you made, but this is not the reason of the crash:





Inside tolowercase() method, the final value of ptr after the execution of the while loop is such that it is pointing to string null (ascii 0). That is why the while loop terminated in the first place. You are returning the same pointer (which now points to 0). So your strcpy() call is trying to copy from a string whose first character is string null.





But while that would result in wrong functionality (cout would print out a blank string), that should not result in a crash. Because if a char* pointer points to 0 (null), even then it is a valid string (of length zero).





But beware of this mistake - once you solve the crash, this mistake will result in wrong functionality.





2. Now for the crash: The crash is probably happening because strcpy's first argument cannot be const char *.





When you declare and assign a string like this:





char * str = "Hello world!";





str becomes a const char *.





If you try to overwrite the contents of a const pointer, it might crash.





Also, tolowercase() method must, by nature, take a non-const pointer as argument, but again you are passing a const pointer as argument. So which one of these reasons is causing the crash is anybody's guess, but your program has serious problems with it.





I could tell you how to overcome these problems, but you should try to solve them youself, now that you know the areas that you need to look at. If you need further help, you can message me. Thanks.
Reply:I dont know C++. But this looks like you are returning a ptr which is NULL from tolowercase. You are increasing the ptr till it becomes null and returning it. Instead you could store the char ptr somewhere in a temp char * (before the loop starts) and return that instead
Reply:Your program tries to change the string in place, one character at a


time, but "Hello, world!" is a constant string and can't be changed.





If the program were technically correct, it would declare str as


const char *const str = "Hello, world!"


because it is really a constant pointer to a constant string.


The compiler would then bark at you when you tried to use


it in a way that changed either the string or the pointer itself.





This rule didn't always exist (or wasn't always enforced), so there are


lots of old code examples that do write over strings like this.





There are a couple of ways around this. One way is to declare str as


a character array and copy "Hello, world!" into it. Another way is to


give tolowercase() two parameters and copy the string into a new


buffer while never changing the old.





But all of these are just teaching exercises. When you really start


programming in C++, you would use std::string and the conversion


would look something like this:





std::string str("Hello, world!");


std::transform(str.begin(), str.end(), str.begin(), tolower)
Reply:#include %26lt;iostream%26gt;





using namespace std;





char * tolowercase(char * ptr)


{


char *temp = ptr;


while( *ptr )


{


*ptr = tolower(*ptr); // Renders lowercase


ptr++;


}


return temp; // This is so the return value is the start of the string not the end.


}





int main()


{


char str[40] = "Hello world!"; // Change this line so that "Hello world!" is stored in the string array. Previously you had a pointer to memory containing "Hello world!".


strcpy (str, tolowercase(str));


cout %26lt;%26lt; str;


return 0;


}





This will work without 'crashing'.


How to include windows.h correctly?

I am using VC++ 2005 standard edition and tried using #include %26lt;windows.h%26gt;


in my project but there are a list of errors with the description:


"error C2872: 'IUnknown' : ambiguous symbol C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\include\unknwn.h "





I found that the windows.h file is in the C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK directory. The project has also included the $(VCInstallDir)\PlatformSDK\lib, \include and \bin lines in the project options window.





How to include windows.h correctly?

How to include windows.h correctly?
Is the program failing on the include? Did you try a simple console program, that does nothing but include windows.h? There is nothing more to it than #include %26lt;windows.h%26gt; and then linking the appropriate libraries.
Reply:Try #include "windows.h"?


How do you loop fscanf until EOF in c?

for example.. number.txt: (has these contents)





1.75:2.00:3.00


2.00:5.00:7.24


3.00:6.35:1.00





--


my source code is..





#include %26lt;stdio.h%26gt;


int main()


{


FILE *infile;


double a, b, c, sum;


char d;





infile = fopen("number.txt", "r");


if(infile == NULL)


{


printf("number DOES NOT EXISTS!");


}


else


{


while(!foef(infile)) /*here's my problem*/


{


fscanf(infile, "%lf%c%lf%c%lf\n", %26amp;a,%26amp;d,%26amp;b,%26amp;d,%26amp;c); /*fscanf is used*/


printf("%f %f %f", a, b, c); /*just for checking*/


sum = a + b + c;


printf("sum is %f", sum);


}





}


fclose(infile);


return 0;


}





--





problem is..





if i put the while loop, it won't compile. it has these error message saying "undefined reference to `foef'".





if i remove the while loop, the fscanf reads only the first line.





i would like to read also the other data from line 2 and line 3 and solve their sum respectively.





so how can i loop the the fscanf?(assuming that i don't know how many lines are in the file? or maybe its safe to say to loop the fscanf until EOF?)


thanks a lot!

How do you loop fscanf until EOF in c?
try feof


it is not foef
Reply:Do this:





while (fscanf(infile, "%lf%c%lf%c%lf\n", %26amp;a,%26amp;d,%26amp;b,%26amp;d,%26amp;c) ){


.


.


.


}





fscanf should return false if it runs out of data

rose