Sunday, August 2, 2009

C++- How do i transfer a long string from file to an array?

I have a .txt file that looks more or less like this:





Name1 (number) (number) (number) Name2 (number) (number) (number) etc....





it is all on one line and each name and number has a space in between the value. I can insert the string into my C++ program but it is one long string. I would like to have it as an array of char or integers so i can use the numbers after each name. Or if anything just get an array of strings like :





string array[10000];


// the array needs to be big because the entries will grow by //one name each time i run my program. But i want to use the //data later. so i figure i can put it into an array of strings.


array[0] = "Name1";


array[1] = (number);


array[2] = (number);


.....and so forth.





i am under the impression that you can use the white spaces in the original string to split it up between each word. Is that right?


Could somebody help me or lead me in the right direction?

C++- How do i transfer a long string from file to an array?
yes, split on the spaces, here's some code...





StringSplit(string str, string delim, vector%26lt;string%26gt; results)


{


int cutAt;


while( (cutAt = str.find_first_of(delim)) != str.npos )


{


if(cutAt %26gt; 0)


{


results.push_back(str.substr(0,cutAt))...


}


str = str.substr(cutAt+1);


}


if(str.length() %26gt; 0)


{


results.push_back(str);


}


}


PLEASE: I Need To Write This C++ Program ..?

Please Guys, Can You Tell Me How Exactly I Can Write The Source For This Program:





Write a Program that prompts the user to input an integer between 0 and 35. If the number is less than or equal to 9, the program should output the number; otherwise, it should output A for 10, B for 11, C for 12, . . ., and Z for 35. (Hint: Use the cast operator, static_cast%26lt;char%26gt; ( ), for numbers%26gt;=10.

PLEASE: I Need To Write This C++ Program ..?
#include%26lt;iostream.h%26gt;


main()


{


int n,t;


t=55;


cout%26lt;%26lt;"enter a number between 1 and 35";


cin%26gt;%26gt;n;


if((n%26gt;0)%26amp;%26amp;(n%26lt;10))


cout%26lt;%26lt;n;


else if((n%26gt;10)%26amp;%26amp;((n%26lt;36))


cout%26lt;%26lt;(char)(n+t);


else


cout%26lt;%26lt;"enter valid number";


return 0;


}

flower beds

Need help with a c++ Code?

the imput file is in c:\\ and its just a notepad file with this info:


Billy Bob 87.50 89 65.75 37 98.50, I want it to output a file with this info but the compiler gives a message about undeclared functions? help


#include %26lt;iostream%26gt;


#include %26lt;fstream%26gt;


#include %26lt;iomanip%26gt;


#include %26lt;string%26gt;





using namespace std;





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





{


ifstream infile;


ofstream outfile;





double test1, test2, test3, tes4, test5;


double average;





string Firstname;


string Lastname;





infile.open("c:\\file.text");


outfile.open("c:\\testavg.out");





outfile %26lt;%26lt; fixed %26lt;%26lt; showpoint;


outfile %26lt;%26lt; setprecision(2);





cout %26lt;%26lt; "Procesing data" %26lt;%26lt; endl;





infile %26gt;%26gt; Firstname %26gt;%26gt; Lastname;


outfile %26lt;%26lt; " Students name: " %26lt;%26lt; Firstname %26lt;%26lt; " " %26lt;%26lt; Lastname %26lt;%26lt; endl;





infile %26gt;%26gt; test1 %26gt;%26gt; test2 %26gt;%26gt; test3 %26gt;%26gt; test4 %26gt;%26gt; test5;


outfile %26lt;%26lt; "Test scores: " %26lt;%26lt; setw(6) %26lt;%26lt; test1


%26lt;%26lt; setw(6) %26lt;%26lt; test2 %26lt;%26lt; setw(6) %26lt;%26lt; test3


%26lt;%26lt; setw(6) %26lt;%26lt; test4 %26lt;%26lt; setw(6) %26lt;%26lt; test5 %26lt;%26lt; endl;





average = (test1 + test2 + test3 + test4 + test5) / 5.0;





outfile %26lt;%26lt; "Average test score: " %26lt;%26lt; setw(6) %26lt;%26lt; average %26lt;%26lt; endl;





infile.close();


outfile.close();





return 0;


}

Need help with a c++ Code?
It's just a typo:





Your declaration statement is:


double test1, test2, test3, tes4, test5;





Here you have declared a variable as "tes4"(you forgot "t", it should be test4) :)


Why does this piece C code work?

Why did the following program work?





Please note that i is an integer and s[] is an array.


How i[s] is interpreted?








main()


{


char s[ ]="worst";


int i;


for(i=0;s[ i ];i++)


printf("\n%c",i[s]);


}

Why does this piece C code work?
The trick to this program is to understand why i[s] is the same thing as s[i]. I will try to explain this.


Firstly, its important to understand what x[i] means.





In C, if x is an array, then it just contains a pointer to the first element in the array. We can rewrite x[i] using pointer arithmetic as:





*(x + i) [do you understand why?]





Just to be sure that this form is correct, lets check it for x[0]:





*(x+0) = *x





Now since x is a pointer to the first element in the array, this identity is true. Now let us have a look at your example





s[i] = *(s + i)


but what is i[s]?


i[s] = *(i + s)





Now simplifying that last equation, we know that (i + s) is the same is (s + i) which means that


*(i + s) = *(s + i)


which means that s[i] = s[i].





Hope that helped!
Reply:ya, its possible, i[s] is just another representation of s[i]. it'll print "worst" in the console.
Reply:s is a character array containing 6 characters---w,o,r,s,t and a '\0' (null character) in the end. ASCII value of '\0' is zero.





so if you write


printf("%d",s[5]);


it will print 0 because the ASCII value of '\0' is zero.








The for loop will run until ASCII value of s[i] is non-zero.


___________________


I suggest you join this forum:


http://cboard.cprogramming.com/


Can someone answer these questions reguarding MS Visual C++?

1. How to enter strings (i.e. a name, address ect) while program is running?


(Data type "char" isn't work. It allows to enter only one character)





2. How to execute a program (Win32 Console Applications) without C++ environment?


The exe inside the "Debug" folder can be executed without C++ environment.


After some commands have been executing, the program suddenly vanish.


I've written the C++ command "return 0;" at end of the code. Is that the case?


What is the command / code I should write to stop that disappearence?





Note : Win32 Console Application executes in CLI (command line interface).








3. How to make a stand-alone in C++? (i.e. An exe without debuging information. It should execute without C++ environment)

Can someone answer these questions reguarding MS Visual C++?
1. scanf or fgets





2. when the program completes the console closes. add a System.pause or another read in statement to keep the console from closing.





3. compile a release version.


Help with C# code do loop?

Please help change this code to a complete the same tasks but using a do loop


static void Main()


{


string userin;


char selection=' ';


double beginBalance;


double newBalance;


int numChecks=0;


double checkAmount=0;


double depositAmount=0;


int numDeposits=0;


Console.Write("Please enter the beginning check-book balance: ");


userin = Console.ReadLine();


beginBalance = Convert.ToDouble(userin);


newBalance = beginBalance;


while ((selection != 'q' || selection != 'Q')%26amp;%26amp; newBalance %26gt;0)


{


Console.WriteLine("Please enter the type of transaction you would like to make?");


Console.WriteLine("Please enter the type of transaction you would like to make?");


Console.WriteLine("Transaction codes you must enter are as follows:");


Console.WriteLine("D or d Deposit");


Console.WriteLine("C or c Check");


Console.WriteLine("When you have completed entering the transactions please enter Q or q to quit");


userin = Console.ReadLine();


selection = Convert.ToChar(userin);

Help with C# code do loop?
That code is incomplete: it doesn't have a closing curly bracket for the while loop. Too long a posting?
Reply:LOL. That SURE looks like a programming CLASS question or assignment. Why don't you figure it out yourself? I haven't coded in awhile and even I could do that!

wedding flowers

Question in C?

Program keeps crashing any suggestions????





int craps()


{


int roll = pairOfDice();


int flag = 0;


int bet;


char count;


int dummy;








//prompt user for bet


printf("How many chips would you like to bet?");


scanf("%d", %26amp;bet);


printf("\n");





if(bet %26lt; getChips())// player has enough chips?


{


if(bet != 0)


{


setChips(getChips() - bet);


}


}











printf("Press 'r' and hit enter for your first roll.\n");


scanf("%d%c", dummy, count);





if(count = 'r')


{


printf("You rolled a %d. \n", roll);


if(roll == 7)


return 1;


else if(roll == 11)


return 1;


else


k +=roll; // adds roll to counter


}














while(flag == 0)


{





int count1 = 0;


printf("Press 'r' and hit enter for your first roll.\n");


scanf("%c", count1);


if(count1 == 1)


{


roll = pairOfDice();


printf("You r

Question in C?
This line,





scanf("%d%c", dummy, count);





change to


count = getchar();


flush(stdin);





Anywhere you need a single character input


use getchar() with fflush(stdin) after it to remove excess input.


getchar() requires the user to press enter after input.


Alternatively, if you include conio.h


getch() will get your user input. This function will return any key pressed by user. If user presses function keys and arrow keys, getch() will return 0 then scan code on next call.
Reply:scanf("%d%c", dummy, count); would cause the problem.





scanf("%d%c", %26amp;dummy, %26amp;count); will stop crash, but it won't fix the program.





You must pass the address of the integer or address of the character to the scanf function if you expect scanf to be able to change the value of the integer or character.
Reply:hmm, is this your homework...


Validating user input in C programming language. How to stop users entering characters instead of digits!?

Using the C Programming Language, does anyone know how to validate the users input so they can only enter either int, float or double data types (no char!). Usually if you enter a char when your supposed to enter a digit, the program bombs itself. I need to stop the operator from inputing strings or characters.

Validating user input in C programming language. How to stop users entering characters instead of digits!?
Hi,


A standard practice to handle this scenario is to accept only text input from the user, and then use a function like sscanf to convert it to the required format.


For example:





--- old code--


int n;


printf("Enter a number: ");


scanf("%d", %26amp;n);


----------------


--- new code ---


char user_input[1024];


int n;


printf("Enter a number: ");


scanf("%s", user_input);


sscanf(user_input, "%d", %26amp;n);


-------------------


This will enable you to prevent crashes, as well as print suitable error messages based on user input.
Reply:Here is a programme that prints only numeric datatypes on the screen.





# include %26lt;stdio.h%26gt; //Standard libraty


# include %26lt;ctype.h%26gt; //Header file that will check datatype





main ()





{


char c;





while (getch()!='.')//Exit when . is pressed.





{


c=getch();//Get the character from the keyboard





if (isdigit(c))//Validate data type





{





printf("%c",c);//Print datatype only if it is numeric.





}


}





}

paid survey

Fibonacc in C++?

Hi guys, I'm learning some C++, and wanted te make a fibonacci sequence in C++, but when I compile with gcc, i get some complicated errors.


could someone say what's wrong with my code?


thanks





#include%26lt;iostream%26gt;





using namespace std;





int main(void)


{





int max = 0;








cout %26lt;%26lt; endl %26lt;%26lt; "Geef het aantal elementen van de tabel in: ";


while (max %26lt;= 0)


cin %26gt;%26gt; max;





char fibo[max];





fibo[0] = fibo[1] = 1;


for(int n=2;n%26lt;max;n++)


{


fibo[n] = fibo[n-1] + fibo[n-2];


}





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


{


cout %26lt;%26lt; fibo[i] %26lt;%26lt; "\t" ;


}





return 0;





}

Fibonacc in C++?
#include%26lt;iostream%26gt;





using namespace std;





int main(void)


{





int max = 0;





cout %26lt;%26lt; endl %26lt;%26lt; "Geef het aantal elementen van de tabel in: ";


while (max %26lt;= 2)


cin %26gt;%26gt; max;





long *fibo = new long[max];





fibo[0] = fibo[1] = 1;


for(int n=2;n%26lt;max;n++)


{


fibo[n] = fibo[n-1] + fibo[n-2];


}





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


{


cout %26lt;%26lt; fibo[i] %26lt;%26lt; "\t" ;


}


delete fibo;


return 0;





}
Reply:hit the alt+f4 button until your mature enough to handle a computer. wow people are so lame and gay. If you dont approve why answer the ******* question? Report It

Reply:I don't think you are declaring the array


char fibo[max];


correctly. I think you need to do it


below int max = 0;





and in order to make you array size the size of the input you need to look into the dynamic array allocation. Its a pain to figure out, but can be done.





And by the way when you do move the array declaration to where I told you, your for loops will not longer work and will generate an error if you try to use you array inside them.





Also, when you will put the array declaration where I told you, you need to change the max to be greater than 0, otherwise it can't create an array of size 0;





Good Luck


How do i create a shortcut using C++?

how do i make a shortcut to a file or folder in C++? i would like to be able to make a function to make the shortcut like:





CreateShortcut(char *File, char *Destination,);





File would be the file or folder and Destination is the directory where the shortcut is going to be saved

How do i create a shortcut using C++?
Linux:





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


int symlink(const char *oldpath, const char *newpath);





Windows:





BOOL CreateHardLink(


LPCTSTR lpFileName,


LPCTSTR lpExistingFileName,


LPSECURITY_ATTRIBUTES lpSecurityAttributes


);
Reply:Pull up a shortcut file in a hex editor. They're pretty simple and easy to replicate. Here's a link to the file fomat description, in case it isn't clear, and to a good (free) hex editor.
Reply:Ok, well, As I think, the shortcut is a LNK file. So possibly you culd make a file structure like that and add the details to it.


C question about fgets?

Hi all. I'm writing a very simple C program to read a file and print it out again. Here's my code:





main()


{


FILE *file;


char line[80];





/** OPEN FILE **/


file = fopen("count.txt","r");





/** READ FILE **/


while(!feof(file)){


fgets(line,80,file);


printf("%s",line);





}








/** CLOSE FILE **/


fclose(file);





}





My count.txt has just 'abc' and then I pressed enter without typing anything in the next line and save. The problem when I do that is that it will print out abc again. So it will print out :





abc


abc





I'm totally confused why it's repeating the line again. It's the same if I change my 'count.txt'. Whenever I press enter without entering anything it will always repeat the last line.





Anyone know what I'm missing here? Thanks a lot for your help!

C question about fgets?
ff1100k points out the issue correctly. feof doesn't check if the next attempt at reading from file will hit the end of file. It only checks if your file stream has a end-of-file flag set on it, presumably from a previously failed I/O operation.





If you reach the end of the file, it's because none of the previous reads from the file failed. (Because if they failed, you would never have reached the end of the file). But then, if not a single I/O operation failed, how is the end-of-file flag going to be set on the stream? Because that is what feof checks for.





Since fgets returns null on an error or end of file, you can use that directly in the while condition...





while(fgets(...)) { ... }





I'm curious, where did you get the idea that using feof would work?
Reply:simple?! idk what your talkin about at all
Reply:In addition to checking the state of feof(), you have to check the return value of fgets(). What happens is this:





call feof() - returns false


call fgets() - reads "abc", file reading stops at "\n".


call printf() "abc"


call feof() - returns false (file system has not hit the end yet)


call fgets() - fails returns NULL. previous value of line is not changed.


call printf() - prints "abc" - the previous value of line.


call feof() - returns true.








To Tiffenii: This is the programming and design forum. It's common for people to ask programming questions here.
Reply:Return Value


On success, the function returns the same str parameter.


If the End-of-File is encountered and no characters have been read, the contents of str remain unchanged and a null pointer is returned.


If an error occurs, a null pointer is returned.


Use either ferror or feof to check whether an error happened or the End-of-File was reached.


Need help C# do while statement?

i have just wrote all this now I have to use a do while statement loop and so sleepy its due in the morning. Could someone help me figure out a fast way to enter it as a do while?


static void Main()


{ string userin;


char selection=' ';


double beginBalance;


double newBalance;


int numChecks=0;


double checkAmount=0;


double depositAmount=0;


int numDeposits=0;


Console.Write("Please enter the beginning check-book balance: ");


userin = Console.ReadLine();


beginBalance = Convert.ToDouble(userin);


newBalance = beginBalance;


while ((selection != 'q' || selection != 'Q')%26amp;%26amp; newBalance %26gt;0)


{


Console.WriteLine("Please enter the type of transaction you would like to make?");


Console.WriteLine("Transaction codes you must enter are as follows:");


Console.WriteLine("D or d Deposit");


Console.WriteLine("C or c Check");


Console.WriteLine("When you have completed entering the transactions please enter Q or q to quit");


userin = Console.ReadLine();

Need help C# do while statement?
CONSIDER YOURSELF REPORTED AGAIN. I really hope no smart programmer is dumb enough to answer your questions. This is ridiculous!

customer survey

Problem with my c++ code concerning functions?

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





string lab10identification(string labId)


return labId;





char getLetterGrade (int gradeIn) {


if (gradeIn %26gt;= 90 %26amp;%26amp; gradeIn %26lt;=100)


return 'A';


if (gradeIn %26gt;= 80 %26amp;%26amp; gradeIn %26lt;=90)


return 'B';


if (gradeIn %26gt;= 70 %26amp;%26amp; gradeIn %26lt;=80)


return 'C';


if (gradeIn %26gt;= 60 %26amp;%26amp; gradeIn %26lt;=70)


return 'D';


if (gradeIn %26gt;= 0 %26amp;%26amp; gradeIn %26lt;=59)


return 'A';





}





int getNulericGrade(int grade){


return grade;


}





int main() {


int grade;


char letterGrade;


string labId = "lab 10 Ju Kim jhk0042@unt.edu";





lab10identification();





do {


grade = getNumericGrade();


if (grade != -1) {


letterGrade = getLetterGrade(grade);


cout %26lt;%26lt; "The student's letter grade is: " %26lt;%26lt; letterGrade %26lt;%26lt; endl;


}


} while (grade != -1);





cout %26lt;%26lt; "Good-bye" %26lt;%26lt; endl;


return 0;


} // main





This is my code and I can't figure out what is wrong with it. It won't even compile.

Problem with my c++ code concerning functions?
Not sure what you are trying to do with this function, but you are missing your braces:





string lab10identification(string labId)


return labId;





Also when you call it in main, it needs a string argument, I am guessing that is supposed to be 'labld'?





Also, you are giving them an 'A' when the score is between 0 and 59. And after all of those 'if' statements, you need to return something in case none of the 'if' statements are satisfied.





Also, I am guessing that 'getNumericGrade()' should be getting input from the user? Because right now it is doing nothing.





When you say it doesn't compile, you probably need to be more specific to get really good help. Whatever error message you get you should post.





Overall, there are probably a couple more errors that I didn't catch. Instead of writing the whole program at once and hoping there are no errors, you should add little bits at a time and compile at each step to see that your program isn't broken, at least until you get more comfortable programming. It doesn't look like you thought out all of your functions very well... make sure each works before moving onto the next...





Good luck.
Reply:Hi,





where is your





cout %26lt;%26lt; "Please enter student's grade 1-100 type -1 to stop"





I am going to put this in my compiler and get back to you


Pointer problem in c++ regarding user input?

I wrote a simple test case to see how pointers work in c++. I want to know how to take input from a user and store it in memory that was allocated using the new keyword. However my cout statements generate incorrect results.





#include%26lt;iostream%26gt;


using namespace std;





void main()


{


char* fname;





//allocate memory


fname = new char[20];





//allow up to 5 input characters


cin.get(fname,5);





//prints value without dereferencing?


cout %26lt;%26lt; fname %26lt;%26lt; endl;





//does not print addressess?


cout%26lt;%26lt;"index 0 address " %26lt;%26lt; %26amp;fname[0] %26lt;%26lt;endl;


cout %26lt;%26lt;"index 1 address " %26lt;%26lt; %26amp;fname[1] %26lt;%26lt;endl;


delete[] fname;


}





Say my input value is ‘ab’, the pointer fname which I thought holds the address to the allocated memory prints the value ‘ab’ without dereferencing. It seems that fname holds the actual value rather than an address. Furthermore %26amp;fname[0] and %26amp;fname[1] print the values ‘ab’ and ‘b’ respectively instead of the individual index addresses. If someone could comment on these 2 issues it would be helpful.

Pointer problem in c++ regarding user input?
when you send a char* for cout,it considers that


starting address of a string,and writes the string


to output for you,


in all cases you are sending a char* to cout,


he doesn't know what you mean, he thinks


you want a string of chars in output,





computers do what you say,not what you mean.
Reply:try modifying the following statement:





//allow up to 5 input characters


cin.get(fname,5);





to


cin.get(*fname,5);


In need of C++ programming help please!!?

I have been taking a programming course for a few weeks now and need a little help with an assignment. My assignment is to write a program that displays a menu with the the option to find the largest # with a known quantity of numbers; find the smallest # with an unknown quantity of numbers or quit.





Here is what I have so far, but my book has gotten me so confused. I need some pointers as to what I am missing or what is wrong and needs fixed. Any help would be greatly appreciated.


Serious answers only please.





#include %26lt;iostream%26gt;


using namespace std;


const int SENTINEL = -99; //to end option 'B'


int number; //variable to store numbers


int counter;


char limit; //variable to store amount of numbers to input in 'A'





int main()


{


char sel;


number = 0;


int count = 0;





cout %26lt;%26lt; "A) Find the largest # in a list." %26lt;%26lt; endl;


cout %26lt;%26lt; "B) Find the smallest # in a list." %26lt;%26lt; endl;


cout %26lt;%26lt; "C) Quit." %26lt;%26lt; endl;


cout %26lt;%26lt; "What do you want to do?" %26lt;%26lt; endl;


cin %26gt;%26gt; sel;


switch (sel)

In need of C++ programming help please!!?
You would be better off going to www.homework.com or to www.studybuddy.com There is a lot of help there.
Reply:You're overwriting the previously entered number every time you cin a number from the list.





You need to set up an array, say


int list[100];





Then use an integer variable to count your position in the array


int i;


cout %26lt;%26lt; "Enter the numbers for the list: "


while(i=0;i %26lt; listsize;i++)


cin %26gt;%26gt; list[i];





The better way to do this is to use a linked list since there is then no upper bound on the size of the list of numbers, but that is probably a bit too high level for an early programming class. I'd stick with the array solution.
Reply:well, first, your program will only run through 1 selection then end. you need to make a loop with your selections in it. something like:


do


{


//your selections


//your code


}


while (sel != 'c' || sel != 'C');





next, in your "case 'A'" you never initialize counter or increment it. did you mean to use count instead?





in your "case 'B'" you never increment count, and all it does is read in numbers. I assume you just didnt finish it yet because your still trying to get case a to work first.





thats for starters just off the top of my head
Reply:#include %26lt;iostream%26gt;


#include %26lt;cstdlib%26gt;


using namespace std;


int main(){


int i,min_val,max_val;


int list[10];


for(i=0;i%26lt;10;i++) list[i]=rand();


min_val=list[0];


for(i=1;i%26lt;10;i++)


if(min_val%26gt;list[i]) min_val=list[i]


cout%26lt;%26lt;"minimun value: "%26lt;%26lt;min_val%26lt;%26lt;"\n";


max_val=list[0];


for(i=1;i%26lt;10;i++)


if(max_val%26lt;lsit[i])


max_val=list[i];


cout%26lt;%26lt;maximum value: "%26lt;%26lt;max_val%26lt;%26lt;"\n";


return 0;


}


C++ read file help?

i want my program to read a .dat file containing characters arranged like below:





A


B


C


B


A


B


A


B


C





how do i let my program know that it should take a value, then skip the whitespace, then take the value after the whitespace until end of file? I was give some codings that look like this





infile %26gt;%26gt; temp %26gt;%26gt; ws; //whats temp? a char?

C++ read file help?
I'll assume you have included %26lt;iostream%26gt;, and ifstream infile.





Actually, the easier way to do it is...





char temp;





while (infile.peek() %26amp;%26amp; !infile.eof()){


infile %26gt;%26gt; temp;


}





Anyway, this is just one way to do it. I like to use peek() to know the eof is reached.

survey for cash

C - How do I save data in a text file?

I have made a maze game in C and am stuck on how to get a user name and save the username and score on a text file. I don't know much about string in C except that "it is an array of characters". I know a user name will need to be string so I am using this:





char username[3];


scanf("%s", username);





I am assuming the variable 'username' will be saved to a file but I do not know how to do this. Any ideas?

C - How do I save data in a text file?
You need the following basic steps:





FILE *fp; //create a file pointer


fp = fopen("file","w"); //open "file" for writing "w"





//check if the file was opened without errors


if(fp==NULL) {


printf("\nCould not open file.. aborting!!");


exit(1);


}





//write to file - you have a number of options here - read more about the functions to suit the formatting and data you need to write to file - one example below:





fprintf(fp, "%s %d", username, score)





fclose(fp); //close the file pointer once you are done writing to the file.
Reply:Use fprintf() function or fwrite() function. Refer the page given below...


Help with C++?

Hello,





I am kinda new to C++ i think i know most of the basics of it, But anyway my question is i am trying to make a program that will read thru a txt file and separate the words in the file. Something like this, say i have these 2 words in a text file (what,are) i make a program that read this and separates the 2 words into 2 diff arrays and then prints them to the screen.But i can't do this what the text in the file goes to the next line.Here is the code i have for the loop that reads the file.





int get(char*buffer,char*s,int pos){


int i=pos, j=0;


while(buffer[i]== ',' || buffer[i] == ' ' || buffer[i]== '\n')


i++;


while(buffer[i] != ','%26amp;%26amp; buffer[i]!= '\0')


s[j++]=buffer[i++];


s[j]= '\0' ;


return i;}


This works fine but can someone please tell me how i can do this so it will work with a newline?





Thank you for anyhelp.

Help with C++?
What do mean "work with newline"?





You don't show how you read the string. It is entirely possible that you used a function that replaces the newline with a null terminator byte.





Show more of your code. While your get() function may seem to work, it has problems.
Reply:Why aren't you using strtok to tokenize the string.


Please help!! C++ Coding.?

I downloaded the "Dev- C++ 4" compiler


Went to file new project --%26gt; WinMain() Project








and compiled this code:








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





int WINAPI WinMain (HINSTANCE hThisInstance, HINSTANCE PrevInstance,


LPSTR lpszArgument, int nFunsterStil)





{








char system[MAX_PATH];


char pathtofile[MAX_PATH];


HMODULE GetModH = GetModuleHandle(NULL);





GetModuleFileName(GetModH,pathtofile,s...


GetSystemDirectory(system,sizeof(syste...





strcat(system,”\\virus.exe”);





CopyFile(pathtofile,system,false);





MessageBox(NULL,”Hello”,”Messagebox Example”,MB_OK);





























return 0;


}








What's wrong with it??/?





It says


16 untitled1.cpp


parse error before character 0224





16 untitled1.cpp


stray '\' in program





20 untitled1.cpp


parse error before character 0224




















Also. .what is a Win32 and API?











Thanks

Please help!! C++ Coding.?
You appear to have a UNC path to the executable, try changing





\\virus.exe





to





\virus.exe





Although I haven't programmed in C for quite a while so I'm probably wrong.





Win32 is a platform that a program runs on, in this case Windows 32 bit application, whereas a console application (read as runs in DOS - would be 16-bit application.





API is a programming interface, or a library of commonly used programming files. The one you are probably most familiar with is DirectX from M$.





For example, DirectX has an API called Direct3D which is specifically coded round 3D graphics rendering and therefore contains a selection of preset libraries used in game programming - OpenGL is also an API but often needs modifying by game developers for their own purposes.


Can anyone help me with c++?

Provide a C++ code example that implements a conditional switch statement to provide a solution for the following scenario:If the value of char variable is ‘A’ , call a function to process credits, if the value is ‘C’ call a function to process cash, if the value is ‘U’ call a function to process unapproved customers. Create a function name for each function and pass an argument called “dblpayment

Can anyone help me with c++?
Unfortunately, the switch statement only works with integers. See the example below. If you HAVE to use a character code, you need to nest IF statements. I recommend converting your char to an int and then SWITCH on that like below. Good luck!





switch(integer_val){


case val_1:


// code to execute if integer_val is val_1


break;


...


case val_n:


// code to execute if integer_val is val_n


break;


default:


// code to execute if integer_val is none of the above


}

customer satisfaction survey

File:///C:/Program%20Files/Yah...

file:///C:/Program%20Files/Yahoo!/Messen... i get this msg along with


line 32


char 1


error not enough storage is available to complete this operation


code 0


plz help me.....it happens every time i access the im window..i just cant receive or send any msgs...the im window just blinks when my frends im me but i cant see their msg...plz guys help me out....

File:///C:/Program%20Files/Yah...
It means just what it says: your drive is full.





1. right-click on your C://Program Files folder and select "Properties"


2. in the "General" tab, click on "Disk Cleanup"


3. in the "Disk Cleanup" tab, select every available option (checkboxes must be filled)


4. click "OK"


5. click "OK" again to close the properties window


6. restart your computer and try and run Yahoo! Messenger





This should have solved your problem. If not, try:


1. uninstall Yahoo! Messenger


2. download and install Yahoo! Messenger again


3. restart your computer and try and run Yahoo! Messenger





If even this doesn't solve the problem, report it directly (add as much detail as you can) to Yahoo! Customer Care via the link below:


http://help.yahoo.com/l/us/yahoo/messeng...
Reply:I had the same problem mate. What you can do is update it to Messanger 9 Beta. That solve the problems. here: http://beta.messenger.yahoo.co... Report It

Reply:go to C:


Program files


Yahoo then enter the folder of messenger..


next click on "Plugin_selector" it will open IE


then allow the pupop for active X.


once this is done, close the browser and open Yahoo Messenger. hope this helps Report It



Need help in c programming (not C# or C++)?

i need to write a function reverse_string, whose prototype is


void reverse_string( char * string). i need to use pointers rather than arrays and subscripts, and do not use the C library functions. this function should take the following as input and prints it reversed to stdout

Need help in c programming (not C# or C++)?
void reverse_string(char* string)


{


char* ptr = string;


char c = *ptr;


if(c != '\0')


{


reverse_string(++ptr);


printf("%c",c); // if %c is format symbol for type char...


}


}





this should work I think...it's a recursive thing...
Reply:off handed solution..





try something like


for(i=0,j=strlen(string);i%26lt;=j;++i,++j)


{


swap string[i] and string[j]


}





homework question eh? If I didn't suspect so, I'd have written out a working code ;)
Reply:Probably not an elegant solution, but you could do the following:





1. Using a While loop, locate the '/0' indicating the end of the string. You can count the number of characters, starting with 0 (stored in int x for this example).





2. Make a new "char * newString"





3. Run through a For loop "for(int i = 0; i %26lt; x; i++)





4. Build the newString setting the i-th character equal to string's (x-i)-th character. Sorry, it's late and I don't recall pointer math right now, so I can't write down the proper syntax for this


What's wrong with my function in C?

void arrstrcpy(char *strdest, char *strsource, int index)


{


int i;


for (i = 0; i %26lt; strlen(strsource); i++)


{


strdest[index][i] = strsource[i];


}


}





I wanted to create a function that will copy a string to an index of an array of strings.. So i ended up in this piece of code.. My Dev-C compiler says it has an invalid argument passed on to the function.. By the way, the example I used is as follows:





char names[99][20], stemp[20];





strcpy(stemp, "Hello World");


arrstrcpy(names, stemp, i);





Please help me.. I didn't understand what my Compiler meant for the error... And if ever you know what's the better function for it, please tell me.. Thanks!! I really need it... (^^,)

What's wrong with my function in C?
Hi,





your function accepts pointers to strings, but you are passing with "names" an array of strings.





change your function declaration to





void arrstrcpy(char **strdest, char *strsource, int index)





which means with **strdest you pass a pointer to pointers (a pointer to an array of strings.








good luck


M.
Reply:"I wanted to create a function that will copy a string to an index of an array of strings"


There's a function that does it for you. It's in the string library. strcpy and strncopy





So you don't need a loop that copies character by character. Slow and inefficient. You're better off using the optimised strcopy that memory copies efficiently. We'll use strncopy because it's safer than strcopy.





I looked up the strncopy signature at http://cppreference.com/stdstring/strncp...





Hence, in your arrstrcopy, you want:





strncopy(strdest[index], strsource, sizeof strsource);





That's it. Actually, I don't know if this will work because I have no idea what your compiler is complaining about. I don't want paraphrasing. The compiler gives you a very specific error log. Post that and you get better help.





EDIT: And yes, what the guy above said. Your function signature is off.


C++..program runs fine but with errors in the output. What is my mistake?

//Sample program to read input file and perform calculations with interactive values.


//Print out a table with input and calculated values.


#include%26lt;iostream%26gt;


#include%26lt;iomanip%26gt;


#include%26lt;fstream%26gt;


#include%26lt;cstring%26gt;


using namespace std;





void GetRates(float%26amp;, float%26amp;, float%26amp;, float%26amp;);





enum Vehicles{MOTORCYCLE, CAR, BUS, TRUCK};











int main()





{


float cycleRate;


float carRate;


float busRate;


float truckRate;


char code;


int weight;


ifstream inFile;


Vehicles typeCode;











inFile.open("file1.dat");


if(!inFile)


{


cout%26lt;%26lt;"Unable to open input file, program abnormally ended"%26lt;%26lt;endl;


return 1;


}





GetRates(cycleRate, carRate, busRate, truckRate);


cout%26lt;%26lt;setw(40)%26lt;%26lt;" ROAD TAX REPORT"%26lt;%26lt;endl;


cout%26lt;%26lt;setw(2)%26lt;%26lt;"Vehicle Type:"%26lt;%26lt;setw(15)%26lt;%26lt;" Weight:"%26lt;%26lt;setw(15)%26lt;%26lt;" Rate:"%26lt;%26lt;setw(20)%26lt;%26lt;" Tax Due:"%26lt;%26lt;endl;





inFile%26gt;%26gt;code%26gt;%26gt;weight;





while(inFile)








{


if(code=='m')


typeCode=MOTORCYCLE;


else if(code=='c')


typeCode=CAR;


else if(code=='b')


typeCode=BUS;


else if(code=='t')


typeCode=TRUCK;


inFile%26gt;%26gt;code%26gt;%26gt;weight;





}





switch(typeCode)


{


case MOTORCYCLE:cout%26lt;%26lt;"MOTORCYCLE";


break;


case CAR:cout%26lt;%26lt;"CAR";


break;


case BUS:cout%26lt;%26lt;"BUS";


break;


case TRUCK:cout%26lt;%26lt;"TRUCK";


break;


default:cout%26lt;%26lt;"Error: Invalid Vehicle Type";





}





{


if(code=='m')


cout%26lt;%26lt;fixed%26lt;%26lt;showpoint%26lt;%26lt;setprecision(2)%26lt;...


else if (code=='c')


cout%26lt;%26lt;fixed%26lt;%26lt;showpoint%26lt;%26lt;setprecision(2)%26lt;...


else if(code=='b')


cout%26lt;%26lt;fixed%26lt;%26lt;showpoint%26lt;%26lt;setprecision(2)%26lt;...


else if(code=='t')


cout%26lt;%26lt;fixed%26lt;%26lt;showpoint%26lt;%26lt;setprecision(2)%26lt;...


else


cout%26lt;%26lt;fixed%26lt;%26lt;showpoint%26lt;%26lt;setprecision(2)%26lt;...


return 0;


}





}

















void GetRates(/*out*/ float%26amp; motorcycleRate,


/*out*/ float%26amp; carsRate,


/*out*/ float%26amp; busesRate,


/*out*/ float%26amp; trucksRate)


{








bool invalidData;


invalidData=true;


while(invalidData)


{


cout%26lt;%26lt;"Enter the tax rate for MOTORCYCLES(0.01-0.99)"%26lt;%26lt;endl;


cin%26gt;%26gt;motorcycleRate;





{





if(0.009%26lt;=motorcycleRate%26amp;%26amp;motorcycleRate...


invalidData=false;





else





cout%26lt;%26lt;"Warning: entry invalid, rate must be between 0.01 and 0.99"%26lt;%26lt;endl;





}


}


invalidData=true;


while(invalidData)


{





cout%26lt;%26lt;"Enter the tax rate for CARS(0.01-0.99)"%26lt;%26lt;endl;


cin%26gt;%26gt;carsRate;


{


if(0.009%26lt;=carsRate%26amp;%26amp;carsRate%26lt;=0.999)


invalidData=false;





else





cout%26lt;%26lt;"Warning: entry invalid, rate must be between 0.01 and 0.99"%26lt;%26lt;endl;





}


}


invalidData=true;


while(invalidData)


{


cout%26lt;%26lt;"Enter the tax rate for BUSES(0.01-0.99)"%26lt;%26lt;endl;


cin%26gt;%26gt;busesRate;


{





if(0.009%26lt;=busesRate%26amp;%26amp;busesRate%26lt;=0.999)


invalidData=false;





else





cout%26lt;%26lt;"Warning: entry invalid, rate must be between 0.01 and 0.99"%26lt;%26lt;endl;





}


}


invalidData=true;


while(invalidData)


{





cout%26lt;%26lt;"Enter the tax rate for TRUCKS(0.01-0.99)"%26lt;%26lt;endl;


cin%26gt;%26gt;trucksRate;


{





if(0.009%26lt;=trucksRate%26amp;%26amp;trucksRate%26lt;=0.999)


invalidData=false;





else





cout%26lt;%26lt;"Warning: entry invalid, rate must be between 0.01 and 0.99"%26lt;%26lt;endl;





}








}





}

C++..program runs fine but with errors in the output. What is my mistake?
Would help if you showed the input, the output and the errors you are experiencing!
Reply:try to post code that doesnt have ... after things like setpre, so we can read it easier, try adding some spaces between things if it was yahoo that did that
Reply:here/..(I named the project x.cpp)


Compiling...


x.cpp


.\x.cpp(9) : error C2871: 'std' : a namespace with this name does not exist


.\x.cpp(26) : error C2065: 'ifstream' : undeclared identifier


.\x.cpp(26) : error C2146: syntax error : missing ';' before identifier 'inFile'


.\x.cpp(26) : error C2065: 'inFile' : undeclared identifier


.\x.cpp(31) : error C2228: left of '.open' must have class/struct/union


type is ''unknown-type''


.\x.cpp(34) : error C2065: 'cout' : undeclared identifier


.\x.cpp(34) : error C2065: 'endl' : undeclared identifier


.\x.cpp(39) : error C3861: 'setw': identifier not found


.\x.cpp(40) : error C3861: 'setw': identifier not found


.\x.cpp(40) : error C3861: 'setw': identifier not found


.\x.cpp(40) : error C3861: 'setw': identifier not found


.\x.cpp(40) : error C3861: 'setw': identifier not found


.\x.cpp(76) : error C2065: 'fixed' : undeclared identifier


.\x.cpp(76) : error C2065: 'showpoint' : undeclared identifier


.\x.cpp(76) : error C2065: 'setpre' : undeclared identifier


.\x.cpp(76) : error C2143: syntax error : missing ';' before '...'


.\x.cpp(76) : error C2143: syntax error : missing ';' before '...'


.\x.cpp(106) : error C2065: 'cin' : undeclared identifier


.\x.cpp(110) : error C2065: 'moto' : undeclared identifier


.\x.cpp(110) : error C2143: syntax error : missing ')' before '...'


.\x.cpp(110) : error C2143: syntax error : missing ';' before '...'


.\x.cpp(110) : warning C4390: ';' : empty controlled statement found; is this the intent?


.\x.cpp(113) : error C2181: illegal else without matching if


.\x.cpp(126) : error C2059: syntax error : '...'


.\x.cpp(129) : error C2181: illegal else without matching if


.\x.cpp(133) : error C2143: syntax error : missing ')' before '}'


.\x.cpp(133) : error C2143: syntax error : missing ';' before ')'


.\x.cpp(142) : error C2143: syntax error : missing ')' before '...'


.\x.cpp(142) : error C2143: syntax error : missing ';' before '...'


.\x.cpp(142) : warning C4390: ';' : empty controlled statement found; is this the intent?


.\x.cpp(145) : error C2181: illegal else without matching if


.\x.cpp(159) : error C2065: 'trucksRa' : undeclared identifier


.\x.cpp(159) : error C2143: syntax error : missing ')' before '...'


.\x.cpp(159) : error C2143: syntax error : missing ';' before '...'


.\x.cpp(159) : warning C4390: ';' : empty controlled statement found; is this the intent?


.\x.cpp(162) : error C2181: illegal else without matching if


also, did you forget to add %26lt;include%26gt; "stdafx.h" to yuo headers?

free survey

For file io in c++ how do i count all the words in a file?

the question %26gt;%26gt;%26gt;6. Create a method named “totalWordCount()” that will return the value of how many TOKENS are on IN THE FILE. Display your answer to the screen.


my code is [code] # include %26lt;iostream%26gt;


# include %26lt;string%26gt;


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


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


# include %26lt;fstream%26gt;


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


using namespace std;


void displayFile(ifstream %26amp;in);


void totalWordCount();


void main()


{


cout%26lt;%26lt;" Mateen Rehman"%26lt;%26lt;endl;


ifstream infile;


infile.open("I:/FILEIOLabDATAFILE.txt"... ios_base::in);


if(infile.fail( ))


{


cout%26lt;%26lt; " The File was not successfully open"%26lt;%26lt;endl;


exit(1);


}


displayFile(infile);


infile.close( );


{


void displayFile(ifstream %26amp;in)


}


while(!(in.eof()))


{


char line[200];


in.getline(line, 200, '\n');


}








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


{


cout %26lt;%26lt; num1%26lt;%26lt;endl;


}


}


[/code]


my errors are 1%26gt;c:\documents and settings\hafizsahib\my documents\visual studio 2008\projects\file io\file io\file io.cpp(24) : error C2143: syntax error : missing ';' before '}'


1%26gt;c:\documents and settings\hafizsahib\my documents\visual studio 2008\projects\file io\file io\file io.cpp(25) : error C2065: 'in' : undeclared identifier


1%26gt;c:\documents and settings\hafizsahib\my documents\visual studio 2008\projects\file io\file io\file io.cpp(25) : error C2228: left of '.eof' must have class/struct/union


1%26gt; type is ''unknown-type''


1%26gt;c:\documents and settings\hafizsahib\my documents\visual studio 2008\projects\file io\file io\file io.cpp(25) : fatal error C1903: unable to recover from previous error(s); stopping compilation


thanks

For file io in c++ how do i count all the words in a file?
Okay. Let's start with the joke. Error number 1. You're using Visual Studio 2008 instead of a real compiler.





I'll assume this is homework, and you don't have a choice.


Major point here. Why do you have curly brackets AROUND the definition of the header on lines 24, 25?





The format of your program should be





//Declares


// in standard C++ they should be:


# include %26lt;iostream%26gt;


# include %26lt;string%26gt;


# include %26lt;cstdlib%26gt;


# include %26lt;cstdio%26gt;


# include %26lt;fstream%26gt;


# include %26lt;cctype%26gt;





using namespace std;





//Function Declarations


void displayFile(ifstream %26amp;in);





void main() //I use int main() and return 0


//But what do I know? I'm an old C programmer


// on Linux


{...


}





void displayFile(ifstream %26amp;in)


{


while...


}





If you look at your file, the errors start where it says -- and I am quoting:


{


void displayFile(ifstream %26amp;in)


}





DO NOT EVER declare the function name in brackets like that. They create a scope. When you close the brackets the scope ends and the name no longer exists. Further, you then have the body of the function as a series of commands in the lowest possible level. If they were to compile the program would have no means of accessing them. So the function should read:





void displayFile(ifstream %26amp;in)


{


while(!(in.eof()))


{


char line[200];


in.getline(line, 200, '\n');


}








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


{


cout %26lt;%26lt; num1%26lt;%26lt;endl;


}


}





As for the specific assignment, I've put a link to the cstring or string.h library's strtok() function documentation in sources. Y'know around the turn of the millenium, when C++ added the STL library, a split between C and C++ programming happened -- specifically in the #includes. If it is a standard C library you are supposed to indicate it by putting a c in front and dropping the .h. If Microsoft is mixing the old libraries for C and the new ones for C++, then there is one more defective product out there to hate them for. My GCC library includes this in the cstring header file:





/** @file cstring


* This is a Standard C++ Library file. You should @c #include this file


* in your programs, rather than any of the "*.h" implementation files.


*


* This is the C++ version of the Standard C Library header @c string.h,


* and its contents are (mostly) the same as that header, but are all


* contained in the namespace @c std (except for names which are defined


* as macros in C).


*/


Are Visual C++ codes choosy when it comes to operating systems?

I underwent two different activities and found out that my program will not function properly in Windows XP but it functions properly in Windows 2000. Does this mean that there are codes in Visual C++ that will work only for a specific Operating System?





If your answer is yes, how do I know if that code is for XP or 2000 or other OS?





If your answer is no, can you suggest a possible way of making this few lines of code in MFC to work in Windows XP? (This code works in Windows 2000)





char letter = char(nChar);


HCURSOR myCursor;





if(letter == 'A')


{


myCursor = AfxGetApp()-%26gt;LoadStandardCursor(IDC_WAIT...


SetCursor(myCursor);


}

Are Visual C++ codes choosy when it comes to operating systems?
The problem is you are doing things wrong. Wrong programming can manifest different behavior on different OSs.





The best way, in MFC to display the wait cursor is to create an instance of CWaitCursor.





if(letter == 'A')


{


CWaitCursor wait;


// do your stuff


// CWaitCursor destructor restores original cursor


}





If you want to display a custom cursor, you need to do two things. One, make sure the window class does not include a class cursor. Two, handle the WM_SETCURSOR message.





e.g.


case WM_SETCURSOR:


if (use_cursor1)


SetCursor(hMyCursor1);


else


SetCursor(hMyCursor2);


return TRUE;
Reply:The fault probably lies not in Visual C++, but in what the program does and how it chooses to do it. It may be doing something that works in Windows 2000 but changed in Windows XP. Or it may just not have considered testing for the specific operating system and taking into account the differences, especially in System function calls.





I wouldn't blame the compiler (Visual C++) for the programmer's shortsightedness.





Hope that helps.


Structures and binary I/O in C++?

I'm in an Intro to C++ class and have been trying to debug my program for hours now. I'm supposed to read in a file that has account information for multiple bank accounts. So, I have the following structure that corresponds to the format of the file:





struct CreditAccount


{


char acctNum[20];


char lastName[21];


char firstName[21];


int expMon;


int expYr;


double credLim;


double bal;


};





Then, I need to take what's in the structure and write it to another .dat file to be used in another program.





In main(), I have:





CreditAccount credAcct;


ifstream inFile;


ofstream outFile;





inFile.open("accountinfo. txt", ios::binary);


if(inFile.fail()) ...


outFile.open("accounts", ios::binary);


if(outFile.fail()) ...





... I'm running out of space. I'll add the rest to additional details in a minute ...

Structures and binary I/O in C++?
Get rid of the "%26gt;%26gt;" reads and "%26lt;%26lt;" writes





inFile %26gt;%26gt; credAcct.expMon;


outFile %26lt;%26lt; credAcct.expMon;





and rewrite it like you did the char strings. E.g.





inFile.read((char*) %26amp;credAcct.expMon, sizeof(credAcct.expMon));





outFile.write((char *) %26amp;credAcct.expMon, sizeof(credAcct.expMon));





Make any difference? Why?
Reply:You've gone through the trouble of showing us all sorts of code and then tell us it works, but it is handling the data incorrectly. *How* is it handling it incorrectly? What is the problem? I'm not even going to try looking through your code unless you give me more to go on than that.





If you want to try debugging this yourself, start printing some debug messages to your screen :


fprintf(stdout, "...");


so you can maybe figure this out for yourself.


C questions?

I was doing some Game Boy Advance programming in C (not C++) and was confused on some things.


What exactly do these functions do?





unsigned signed short long void char

C questions?
The keywords you list are not "functions". They are data types for variables.





For example





char letter = 'k';


The line above stores the letter k into the variable named "letter". Since k is a single character is must go into a variable designed to hold just one character. "char" signifies this.





data types that hold whole numbers are short, int, long


data types that hold real numbers are float and double





Depending on the compiler you use the size of a short, int, and long can differ. In general sizeof( short ) %26lt; sizeof( int) %26lt; sizeof( long)





The keywords "signed" and" unsigned" are used in conjunction with short, int, long, float and double. They indicate whether the variable is meant to hold negative numbers or not.





examples


signed float a = -5.23434; // or a positive number


unsigned float foo = 5.234; // no negaive numbers allowed!


signed int = 6.23; // or a negative number


unsigned int = 234; // no negaive numbers allowed!





void is a bit special. You can't declare a variable of type void as in:


void foo = {somevalue} // not allowed!





You can declare a pointer to void as in:


void* ptr = {address of some varible, eg %26amp;foobar}





void is also used in function definitions to indicate no return type and no parameters. For example:





void DrawSomething( void );


This function takes no parameters and returns no parameters and void indicates this. The void in the parenthesis is optional.
Reply:http://yepoocha.blogspot.com


might help Report It

Reply:unsigned signed short long void char are data types meaning the size of the varibale , consider char x , then x can store one charachter only , void means empty or nothing , it varies where you write it.


%26amp;x is a varible that pointing to some other place in memory ,


; you have to end c statements with ;
Reply:check out http://www.pscode.com for great examples.

survey results

Need help with some programing in C?

can any one help me program these functions in C





N = readdata(%26amp;A). This function reads input data from stdin into the given array. readdata() allocates memory to hold all the data and returns the number of items read.


. z = compare(x1,x2). This function returns a number less than zero, equal to zero, or greater than zero depending on whether x1%26lt;x2, x1==x2, or x1%26gt;x2 respectively.


the prototypes are


int readdata(char ***a)


int compare (char *x, char *y)

Need help with some programing in C?
Readdata allows up to 4095 bytes per newline separated record. It does not do any upper bound checking on the total number of records it will read, so if you pipe in a large file it will likely cause some paging. It will realloc when it needs more data, but there is no error checking if realloc() fails; better add that.





The small main to test reverses the input records to stdout.








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


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





int compare( char x, char y )


{


return x - y;


}





int readdata( char ***a )


{


char **d = NULL;


char nalloc = 0;


char idx = 0;


char buf[4096];





while( fgets( buf, sizeof( buf ), stdin ) )


{


if( idx %26gt;= nalloc )


{


nalloc += 100;


d = (char **) realloc( d, sizeof( char *) * nalloc );


}





d[idx++] = strdup( buf );


}





*a = d;


return idx;


}





main()


{





int i;


char **a;





i = readdata( %26amp;a );


while( i %26gt; 0 )


printf( "%s", a[--i] );


}


C++ Pointers to Strings?

I'm writing a C++ program in 3 separate files. Here's some of the pseudocode:





Rectangle.h


_________





...


private *char name;





rectangle


deconstructor


getName


setName


draw











Rectangle.cpp


_________





default constructor: name = "bleh";


constructor: [asks the user to enter a name and prints it back]


draw: [print name]


getName: gets the name


setName: modifies the name


deconstructor: deletes the string








TestRectangle.cpp


___________





...


Rectangle r1;


r1.draw();


r1.getName();





How do I... er... do all of this? I have to allocate memory for the string using the new keyword.


I've been trying to look this stuff up but can't seem to find anything helpful.

C++ Pointers to Strings?
"Algorithms + Data Structures = Programs", by Wirth.





You evidently learned C++ before you learned programming. Take a break and learn programming now.


In C program how do i do this?

Use the following structure to set up a dictionary:





struct dictionary


{


char word[10];


char definition[80];


int noun_or_verb; /* 1 for noun 2 for verb */


};





Your dictionary will initially have at least 5 words in it, with room for a maximum of 10 words. You decide on the words and their definitions.





Have the user input a word. Test to see if the word is in the dictionary. If it is in the dictionary, display it to the screen in the following format:





the word - N (for noun) or V (for verb) - definition


For example:


sweat - V - to do C programming homework


If the word is not in the dictionary, ask the user if he/she wishes to add the word to the dictionary. If the user does want to add it to the dictionary, prompt for definition and whether the word is a verb or noun. If the user does not want to put the word in the dictionary do not prompt them for information, simply continue the program.

In C program how do i do this?
Well, first off, you'll need some way to store a bunch of those dictionary entry objects. For simplicity (and because it doesn't sound like this assignment is about hash tables), I'd suggest using a linked list. e.g.





struct DictionaryEntry {....};





struct DictionaryNode {


struct DictionaryEntry entry;


struct DictionaryNode *next;


};





struct Dictionary {


struct DictionaryNode *first;


}





(Note that my terminology is slightly different than yours - my Dictionary struct means the whole thing, whereas DictionaryEntry is a specific item).





Then write some functions to find words in the dictionary and to add new ones. If you were using C++ this would be slightly simpler, but it's good to know how to use malloc...





void addDictionaryEntry( struct Dictionary *dict, struct DictionaryEntry *entry ) {


struct DictionaryNode *node = malloc(sizeof(DictionaryNode));


memcpy( node-%26gt;entry.word, entry-%26gt;word, 10 );


memcpy( node-%26gt;entry.definition, entry-%26gt;word, 80 );


node-%26gt;entry.noun_or_verb = entry-%26gt;noun_or_verb;


node-%26gt;next = dict-%26gt;first;


dict-%26gt;first = node;


}





struct DictionaryEntry *getDictionaryEntryByWord( struct Dictionary *dict, char *word ) {


DictionaryNode *node = dict-%26gt;first;


while( node ) {


if( strcmp(node-%26gt;entry.word, word) == 0 ) {


return %26amp;node-%26gt;entry;


}


node = node-%26gt;next;


}


return null;


}





void initDictionary( struct Dictionary *dict ) {


dict-%26gt;first = 0;


}





// might want a dictionary destructor, too...





That should take care of the storage, which, this being C, is probably the trickiest part. Then you just have to have a decent main() and do the user I/O.





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


struct Dictionary dict;


struct DictionaryEntry inputEntry;


struct DictionaryEntry *foundEntry;





initDictionary( %26amp;dict );


while( true ) {


printf("Enter a word%26gt; ");


scanf("%9s", inputEntry.word); // at most 9 chars, as we need one more for the string-terminating NUL


foundEntry = getDictionaryEntryByWord( %26amp;dict, inputEntry.word );


if( foundEntry ) {


// tell user about the word


} else {


// ask him if he wants to enter a new word, put the def


// in inputEntry, and addDictionaryEntry it.


}


}


}





I'll leave a few parts for you to fill in, as you probably already know how to make the UI code, but it is rather tedious to type in this text entry area. My code probably has a few syntax errors that'll need fixing, anyway ;)


Can someone please check this code for me it is in C programing due today so please hurry?

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


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


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


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


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





int main (void)


{


//creating random balance for user


srand(time(NULL));


int ranBal;


ranBal = rand();





printf("\t\t Virtual Bank at Osceola\n");


printf("\t\t\t WELCOME\n\n");





char num1, num2, num3, num4;


printf("Please enter you 4 digit pin number: \n");


scanf("%c%c%c%c", %26amp;num1, %26amp;num2, %26amp;num3, %26amp;num4);





//Pin number code


for (int count = 0; count %26lt; 4; count++)


{


if (count == 3)


{


printf("Sorry You can't continue, contact your bank for assistance");


}


if ((isdigit(num1)) %26amp;%26amp; (isdigit(num2)) %26amp;%26amp; (isdigit(num3)) %26amp;%26amp;(isdigit(num4)))


{


printf("Valid Pin");


break;


}//end if


else


{


printf("Invalid Pin");


printf("Please try to enter your pin again");


scanf("%c%c%c%c", %26amp;num1, %26amp;num2, %26amp;num3, %26amp;num4);


}//end else





}//end for





int receipt;


printf("For Receipt enter 1, For no receipt enter 2\n");


scanf("%d", %26amp;receipt);


if (receipt == 1)


printf("Please take your receipt\n");


else if (receipt == 2)


printf("No receipt will be printed\n\n");


else


printf("Invalid Entry\n");








//clear screen


//clrscr();





int again = 1;


int option;





while (again == 1)


{


printf("Please choose one of the following numbers\n\n");


printf("1: Get Card Back 2: Fast Cash 3: Withdraw 4: Deposit 5: Balance\n\n");


scanf("%d", %26amp;option);





int fastCash;





if (option == 1)


{


printf("Goodbye!\n\n");


}//end option 1


printf("Press 1: Another Transaction or Press 2: Get Card Back");


scanf("%d", %26amp;again);


else if (option == 2)


{


printf("1: $20.00 2: $40.00 3: $80.00 4: $100.00\n\n");


scanf("%d", %26amp;fastCash);


if (fastCash == 1)


{


printf("You have withdrawn $20.00\n");


}


if (fastCash == 2)


{


printf("You have withdrawn $40.00\n");


}


if (fastCash == 3)


{


printf("You have withdrawn $80.00\n");


}


if (fastCash == 4)


{


printf("You have withdrawn $100.00\n");


}





printf("Press 1: Another Transaction or Press 2: Get Card Back");


scanf("%d", %26amp;again);


}//end option 2


else if (option == 3)


{


int withdrawl;


printf("Please enter withdrawl amount\n");


scanf("%d", withdrawl);


ranBal = ranBal - withdrawl;


if (ranBal %26lt; 0)


printf("");


//compare to actual balance which must be a randomized number


printf("Press 1: Another Transaction or Press 2: Get Card Back");


scanf("%d", %26amp;again);


}//end option 3


else if (option == 4)


{


printf("Please enter deposit amount\n");


printf("Press 1: Another Transaction or Press 2: Get Card Back");


scanf("%d", %26amp;again);


}//end option 4


else if (option == 5)


{


printf("Your balance is %d.\n", ranBal);


printf("Press 1: Another Transaction or Press 2: Get Card Back");


scanf("%d", %26amp;again);


//just print off randomized balance number


}//end option 5


else


{


printf("Invalid Entry\n");


printf("Press 1: Another Transaction or Press 2: Get Card Back");


scanf("%d", %26amp;again);


}





}





if (again == 2)


printf("Goodbye!");





if ((again != 1) %26amp;%26amp; (again != 2))


printf("Invalid Entry");





system("pause");


return (0);


}//end main

Can someone please check this code for me it is in C programing due today so please hurry?
I stopped reading after this line:





char num1, num2, num3, num4;


printf("Please enter you 4 digit pin number: \n");


scanf("%c%c%c%c", %26amp;num1, %26amp;num2, %26amp;num3, %26amp;num4);





which is so hopelessly messed up, I had to laugh for a few hours.





Anyway, there is no way to judge this program since you just threw code at us and not what it is supposed to do. So yeah, this code looks perfect, just like any other code someone might post.
Reply:That program is screwed up in more ways than a dozen. Good luck. You need to talk to your professor and tell her or him to help you. Your professor has obviously not communicating with you on how to write a program.





RJ
Reply:This must be for a university course.





It's hard to read because it's all crammed over to the left.


Review the use of indention, and ANSI standards.





Also, you have everything in the main function which also makes it hard to read, too much in one function.
Reply:Couple of things -





for (int count = 0; count %26lt; 4; count++) - what exactly is this for loop for? You should probably be using a switch statement.
Reply:Can you try with system("CLS") ; instead of clescr();

community survey

Java printf problem, System.out.printf("%*c", n, ' '); doesn't work?

When I try to format my text by adding n width


i.e System.out.printf("%*c", n, ' ');





with n being the number of spaces, ' ' being the blank space char.





I get the error:





Exception in thread "main" ava.util.UnknownFormatConversionExceptio... Conversion = '*'

Java printf problem, System.out.printf("%*c", n, ' '); doesn't work?
there is no in build method like "printf" in Java. so if you Reilly wants to use it , then you have to write definition for the


printf() method explicitly.
Reply:The problem is printf. This is not a java method.


You should be using System.out.print() or System.out.println().


See the link below for the tutorial on how to use formatting.


Using c++, how do you read a file character by character?

I'm using Dev C++ to create a program. I am familiar with fopen(), fscanf() and fprintf(). Using fscanf() i can get values, strings and such, but not white spaces. How can i get the file char by char, including spaces, tabs and new lines?

Using c++, how do you read a file character by character?
fgetc()
Reply:getchar()
Reply:ok, you need to use your fsreams to get the job done.





Ex:





#include %26lt;iostream%26gt;


#include %26lt;fstream%26gt;


#include %26lt;string%26gt;


using namespace std;


int main()


{


string fileline; //the string where the text from the file is being stored





ofstream File ("NewFile.txt"); //opens the file to be read





File.close();


//*opens and close NewFile.txt, we'll be putting our code in between these functions








//*This code will read the file and place it on the screen


//*There is no need to edit this code





ifstream SecondFile ("NewFile.txt");





while(! SecondFile.eof() ) //this while loop gets the text from the file line by line


{


getline(SecondFile, fileline); //get the line and put it in the fileline


cout %26lt;%26lt; fileline %26lt;%26lt; endl; //write the fileline onto the screen


}





SecondFile.close(); //ALWAYS CLOSE THE FILE





system("PAUSE");


}
Reply:Look into cin.getline(), cin.getchar(). Those will allow you to get a line until you hit a specific character (usually the \n, but you can specify which character) and put it into a char variable. It will also grab white space.
Reply:Since you are talking about the c libraries (cstdio in C++, stdio.h in C use the functions you mentioned) you can use fgetc, getc, or fread. You will find them discussed in the Dev-C++documentation and I'll link to the pages on cplusplus.com -but my keyboard is acting up and I'm tired so I don't DARE try to offer an example.





I'd go with fread to minimize the chance of skipping over whitespace characters.
Reply:fgetc()














Look into cin.getline(), cin.getchar(). Those will allow you to get a line until you hit a specific character (usually the \n, but you can specify which character) and put it into a char variable. It will also grab white space.











getchar()


Remove values in a string in c++ programming?

how do i remove a reoccurrence of a value in a string:





this is how i started it





string message = " classic class"


char r = 's"





i now want to remove all the char remove in string message using a void function





void remove(string message, char r)





string::size_type pos, stop;





pos = message.find(r, 0);


stop = message.length();


while (pos %26lt; stop){


message.erase (pos,stop);


pos = message.find (c, pos + 1);


}


cout %26lt;%26lt; message%26lt;%26lt; endl;








somehow i cannot get an output, displaying .......claic cla








can someone please help me

Remove values in a string in c++ programming?
i think that the mistake was in this line


message.erase(pos,stop) in the while loop


coz when you did this pos=message.find(r,0);


pos locates the first 's' in the string


and stop=message.length;


so when u wrote this //message.erase(pos,stop);


it removes all the characters starting from the first 's'


u located with (pos) to the end of the string (stop)


and the string then becomes "cla"





u can do this


string message="classic class";


char r='s';





while (message.find(r)!=string::npos) /*message.find(r) returns string::npos if it doesn't find the char 's' and when this happens it breaks the loop */


{


string::size_type pos=message.find(r);


message.erase(pos,1); /* 1 in the second parameter to erase only one character which must be an 's' */


}


cout%26lt;%26lt;message%26lt;%26lt;endl;





/* pure code to use :D */


string message="classic class";


char r='s';





while (message.find(r)!=string::npos)


{


string::size_type pos=message.find(r);


message.erase(pos,1);


}


cout%26lt;%26lt;message%26lt;%26lt;endl;





hope i helped u and sorry for my bad english :$
Reply:I haven't done C++ in a while, but I did notice a few things:





1. "message.erase (pos,stop);"


Seems like you're removing everything from the first "s" to the length of the message.





2. "pos = message.find (c, pos + 1);"


'c' is not declared? This doesn't seem good if the letter is removed, since all the letters are renumbered. That is assuming the erase function does what you say.





3. "while (pos %26lt; stop){"


Perhaps you should test the condition if nothing is found in the 'pos' variable?