you are using char pointers... therefore, ye' are using null-terminated character arrays.
trust me.
you are using char pointers... therefore, ye' are using null-terminated character arrays.
trust me.
i'll do one for you just to get ye' started:
//using pointer arithmetic
int string_length_1(char* cstring)
{
int size = 0;
while(*cstring != NULL)
{
//increment the pointer
cstring++;
size++;
}
return size;
}
//Same function using array subscripts
int string_length_2(char cstring[])
{
int index = 0;
//using array subscript
while(cstring[index] != NULL)
{
index++;
}
return index;
}
your string copy functions will also be just as simple: pass two arrays into your function. use a loop to copy 1 array into another, element by element.
one thing about your assignment... although it seems overwhelming with all the detailed instructions, he is actually making it easier for you.. leaving you with little guess work on your part. (he gives you all the functions you will need for example.)
is it safe to assume that what you can run on a computer will also run on your uncle's billboard
i'll do it if you make it worth my while.
I purposely made this close to what you want, but not exactly what you wanted... just so you can attempt to resolve minor issues like this on your own. you have my idea of a concept i think you should use, which is 90% of the task. make an attempt. make some psuedo code of what you want to do, and translate it into c++.
if nothing else, show us your attempts, and we will kinda point ye' in the right direction.
all of this is to ensure that we do not have to figuratively spoon feed you, or hold your hand when crossing the street.
you are a big boy now.
this would actually be a better way to do it once you get to the boundaries of the array:
//RECURSIVE EXIT CASE
//Test for ANY valid possible move, if none exit function
if(!turns || (board[row+1][col]!='0' && board[row][col+1]!='0'
&& board[row-1][col]!='0' && board[row][col-1]!='0'))
{
cout << "\nNo more available moves. " << endl << endl;
return;
}
this may not be perfect, but it's better than that crap i just gave you. tweak it, debug it, take the concepts and run with it:
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
void random_step_generator(int& turns, char board[5][9], int& row, int& col);
void display(char board[5][9]);
int main()
{
char board[5][9];
int turns = 0;
int row = 2;
int col = 4;
char ans = '\0';
srand(time(NULL));
do{
//make everything '0'
for(int i=0; i<5; i++)
for(int j=0; j<9; j++)
{
board[i][j] = '0';
}
//starting position
board[row][col] = '*';
//prompt user for number of random steps to take from middle
cout << "\nEnter number of random steps to take ";
cin >> turns;
random_step_generator(turns, board, row, col);
display(board);
cout << "Would ye' like to try again? (Y/N) ";
cin >> ans;
row = 2;
col = 4;
}while(ans == 'y' || ans == 'Y');
return 0;
}
//call a recursive function to populate the board with a random steps
void random_step_generator(int& turns, char board[5][9], int& row, int& col)
{
int direction = 0;
//RECURSIVE EXIT CASE
//Test for ANY valid possible move, if none exit function
if(!turns || (board[row+1][col]=='*' && board[row][col+1]=='*'
&& board[row-1][col]=='*' && board[row][col-1]=='*'))
{
cout << "\nNo more available moves. " << endl << endl;
return;
}
//0=up, 1=right, 2=down,3=left
enum{up, right, down, left};
direction = rand()%4;
if(direction == up && board[row+1][col]=='0' && row)
{
board[++row][col] = '*';
}
else if(direction == right && board[row][col+1]=='0'&& col<8)
{
board[row][++col] = '*';
}
else if(direction == down && board[row-1][col]=='0' && …
//initialize a 2D array
char board[5][9];
//make everything '0'
for(int i=0; i<5; i++)
for(int j=0; j<9; j++)
{
board[i][j] = '0';
}
//prompt user for number of random steps to take from middle
//call a recursive function to populate the board with a random steps
void random_step_generator(int& turns, char& board[][], int& row, int& col)
{
//RECURSIVE EXIT CASE
//Test for ANY valid possible move, if none exit function
if(!turns || board[row+1][col]=='1' || board[row][col+1]=='1'
|| board[row-1][col]=='1' || board[row][col-1]=='1')
{
cout << "\n\nNo more moves. ";
return;
}
//0=up, 1=right, 2=down, 3=left
enum{up, right, down, left};
direction = rand()%4;
switch(direction)
{
case up:
board[row+1][col]=='0'?board[++row][col]=='1':random_step_generator(turns, board, row, col);
break;
case right:
board[row][col+1]=='0'?board[row][++col]=='1':random_step_generator(turns, board, row, col);
break;
case down:
board[row-1][col]=='0'?board[--row][col]=='1':random_step_generator(turns, board, row, col);
break;
case left:
board[row][col-1]=='0'?board[row][--col]=='1':random_step_generator(turns, board, row, col);
break;
}
//Display the move
display();
//Recursive call
random_step_generator(--turns, board, row, col);
}
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int counter = 1;
int left_space = 20;
int offset = 0;
cout << setw(20) << '*' << endl;
for(int i=0; i<10; i++)
{
cout << setw(--left_space) << '*' << setw(offset+=2) << '*' << endl;
counter += 2;
}
cout << setw(9);
for(int i=0; i<23; i++)
{
cout << '*';
counter++;
}
cout << "\n\nThis triangle is made of " << counter << " stars. " << endl;
return 0;
}
like, what do ye' need help with dude¿
short int or int for example, would be a 'standard' or most commonly used among the native c++ variables.
Here is a general progression for using large numbers:
1. use a standard variable
2. use a long variable
3. use an unsigned long variable
4. split the number is several variables
5. use a c-string buffer
6. use an aggregate data type
7. use a library or dll for handling large numbers
8. upgrade hardware locally to enhance physical and/or logical memory
9. use a database or internet API
it can go as high as you need it to go. there is no limitation. even if hardware limitations are exceeded, ye' can still use a net based resource, which is limitless.
Looks like you got a lot of the file I/O handled.. i'll just give ye' a little psuedo to get you on your way:
//Load your files into int[20] arrays
for(int i=0; i<20; i++)
{
file1 >> array_one[i];
file2 >> array_two[i];
}
//Multiply each array, element-by-element and save results in an int[20]
for(int i=0; i<20; i++)
{
results[i] = array_one[i] * array_two[i];
}
//Write results[20] to the output file.
this is a c++ forum.
this is not a c forum.
Now that i think about it, try
file >> *elements[i];
what seems to be the problem senor
should be:
//display
for(int i=0; i<number_of_elements; i++)
{
cout << *element[i] << endl;
}
if you ever take assembly language, you'll get a little insight on how arrrays and 2D arrays are really handled in memory. it does appear that line #31 looks like a 1d array; but i think it is ok. you could just as easily write it as: file[elements][0] but it will resolve to the same memory location as file[elements].
each element[] is just a pointer to the starting memory position of a 15 char buffer.
element[starting_memory_address][15_char_buffer]
so after your array is loaded, you could just easily do this and list all the elements of the periodic table:
for(int i=0; i<number_of_elements; i++)
{
cout << element[i] << endl;
}
because you are outputting a cstring at it's starting memory position. output will stop at the null terminating character.
perhaps the problem is compiler dependent; try changing line #31 to element[0] and see if that helps.
lines #20 and #21....
Elements = new char*[maxlines];//initialize pointer to pointer
symbol = new char*[maxlines];
also, you are not allowing space for a null terminating character when you declare symbol = new char[2] because periodic symbols are usually two characters.. leaving no space for a null terminator in your c-string. it should at minimum be symbol = new char[3].
ye' need to enclose your if() case in curly braces;
if(something)
{
//do stuff
}
else if(something)
{
//do other stuff
}
else
{
//do something else
}
simple mistake.
in line #21, are you reading in 'maxlines' every loop iteration? is this necessary? also, lines #22 and #23 you are re-allocating memory for 'element' and 'symbol' each loop iteration. Instead, try allocating the memory once, when the variable is declared. Then, every time you make a read operation, store the results into another container, perhaps a vector<char*>.... or even declare a 2D array:
//2D dynamic array of character arrays
//Element[number_of_elements][longest_word_length]
//Initialize a 'pointer to a pointer'
char** element = new char*[number_of_elements];
//allocate memory
for(int i=0; i<number_of_elements; i++)
{
element[i] = new char[longest_word_length];
}
//read in from text file
int counter = 0;
while(infile)
{
infile >> element[counter];
counter++;
}
Make sure the second dimension of the array can accommodate the longest word + 1 null terminating character. you may even consider and extra amount of 'padding' just to ensure there are no problems exceeding the bounds of your arrays.
also, i would recommend using string class objects in order to avoid having to do all this memory allocation crap.
from what I understand, you wish to read in a line from a text file, and parse it into several useful parts. One method is to read in the text file, 'line at a time' and then split the line up into tokens. This method is useful when your text file may not always strictly adhere to a standard format (random text for example, like a love letter from your girlfriend)
string line;
string target;
int line_counter = 0;
int pos = 0;
//ask user what they be lookin' for
cout << "Enter something to find within' ye' text file: ";
cin >> target;
while(infile && pos != string::npos)
{
//set line counter
line_counter++;
//read in entire line of text
getline(infile, line);
//attempt to find what ye' be lookin' for (as in your example, ye' wish to find 'aa')
pos = line.find(target);
//if found
if(pos != string::npos)
{
cout << target << " found at position " << pos << " in line #" << line_counter << " of the text file. ";
}
}
//if not found
if(pos == string::npos)
{
cout << target << " not found in ye' text file. ";
}
This method allows ye' to specifically test and identify specific parts of your text file, even if it's all random. The code I provided was based on this example.
Another way to get the parts ye' need out of ye' text file, is to read the entire file 'word …
if I recall correctly, the stdio.h library is just an antiquated C version of the modern <iostream> C++ version. it may or may not have file handling properties.. I don't know because I have almost no C experience; however, you should focus on modern coding practices, such as staying away from the old C .h libraries (generally speaking of course)
cout << "How many seconds did ye' object fall? ";
cin >> seconds;
for(int i=0; i<seconds; i++)
{
distance += .5 * g * pow(t, 2);
}
cout << "\nTotal distance traveled: " << distance;
This is enough to get you thinkin'. There are some obvious unanswered questions here, but it's enough for you to figure it out. Cause I just did 90% of the work for you.
Edit: fixed a bunch of mistakes. sorry, i do most of this stuff in my head... which unfortunately is not a good debugger.
my bad.
//Some of the vars you'll need
fstream infile;
string temp;
vector<string> unique_words;
vector<int> word_counters;
int words = 0;
//Here are some functions you might need
bool is_unique(string, vector<string>);
string strip_punct(string);
string make_lower(string);
int get_position(string, vector<string>);
//Here is the beefy part of the program, just to get ye' started
while(infile)
{
//Read in a word from the text file
infile >> temp;
//Strip away any punctuation
temp = strip_punct(temp);
//Make all lower case (for comparison reasons)
temp = make_lower(temp);
//If the word has never been used, add it to the 'unique_words' vector
if(is_unique(temp, unique_words))
{
//Increment counter of number of words in 'unique_words' vector
words++;
//Add the new word to the vector of unique words
unique_words.push_back(temp);
//Add one more element to your 'vector of counters'
word_counters.resize(words);
//Increment the counter corresponding to your newly added word
word_counters[words]++;
}
else //Word has been used before
{
//Get position of existing word
pos = get_position(temp, unique_words));
//Increment its counter
word_counters[pos]++;
}
}
Here is the pseudo for what ye' are wanting to do:
1. open the text file
2. perform error handling; check if file open was successful.
if unsuccessful, handle accordingly.
//Begin Loop//
3. using a loop, push each word into a temp_string.
4. pass the temp_string into a function that will strip away any punctuation.
5. pass the temp_string into a function that will make all letters lower-case.
6. pass the temp_string into a function that will determine if the string is already in a vector containing the text file. you can loop through every element of the vector to make a comparison, or use the find function in <algorithm>
7. if word is unique, push it into a vector of unique words.
8. if word is not unique, increment an identical vector<int> that corresponds to the vector of unique words; each element serving as a counter of the number of occurances each word being used in the text file.
//End Loop//
9. display ye' results
10. close fstream objects.
//Some of the vars you'll need
fstream infile;
string temp;
vector<string> unique_words;
vector<int> word_counters;
int words = 0;
int size = 0;
//Here are some functions you might need
bool is_unique(string, vector<string>);
string strip_punct(string);
string make_lower(string);
int get_position(string, vector<string>);
//Here is the beefy part of the program, just to get ye' started
while(infile)
{
//Read in a word from the text file
infile >> …
how can I read specific data from file?
I have designed my own method which involves stepping through each character of a text file once and recording the position of all the new lines, but I think someone else might have a more efficient method.
Or.. you can just push the entire text file into a vector (or something similar) and perform searches on the data ye' wish to find.
how can I make program to insert "something2" (without quotes) into something[0] string and "something3" into something[1] string? so my program will get everything after "Something:" and between quotes
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
fstream infile;
int counter = 0;
string text_file[10];
infile.open("text.txt");
if(!infile.is_open())
{
cout << "\aError! File not found.";
cout << "\nFile may have been deleted, moved, or renamed.";
cout << "\nPress [ENTER] to continue... ";
cin.get();
}
while(infile)
{
infile >> text_file[counter];
counter++;
}
infile.close();
return 0;
}
intitialize = 25. which means your array is set to [0] thru [24]. in your code, scorsin >> scoresArray[initialize] is like saying scorsin >> scoresArray[25].... which is out of bounds of your array. you are attempting to access memory that isn't allocated to you. additionally, you are trying to read your entire text file into a single element of your array (array[25]). So, to summarize, you are attempting to read an entire text file into a single element of an array... that isn't even allocated to you. Solution: use a counter to step through the array everytime you make a read operation from your text file. Then, increment your counter each subsequent loop through your array. Finally, ensure your counter stays less than 25, because 25 will take you out of bounds of ye' array.
Ye' never state what ye' problems is, but i'll guess it has something to do with float precision. there are a couple o' ways to set precision:
cout << setprecision(2);
// or
cout.setf(ios::fixed);
cout.setf(ios::showbase);
cout.precision(2);
please, dont be shy. tell us what ye' problem be.
Arrr matey, the error of ye' ways be in lines #35 & #37. Yarrrr.
in my opinion, you should write your own function specific for testing cases where input is strictly 'all consonants', and handle this case accordingly.
just because your teacher didn't put this in your assignment doesn't mean ye' shouldn't take the initiative.
Your general program outline will probably look something similar to this:
#include<iostream>
using namespace std;
//Function prototypes
int prompt();
double calculate_commission(double& commission);
//main driver
int main()
{
//local function variable declaration(s)
double commission = 0.0;
//main loop
while(prompt())
{
calculate_commission(commission);
}
return 0;
}
//Function Definitions
int prompt()
{
/* you write this */
}
double calculate_commission(double& commission)
{
/* i helped you enough,
now it's time to help ye'self
*/
}
try this:
#include <windows.h>
//Declare a 'handle' type object
HANDLE console_handle;
//Get the 'handle' of the console window
console_handle = GetStdHandle(STD_OUTPUT_HANDLE);
//Change the title bar text
SetWindowText(console_handle, "I want to be the very best.");
Here is a reference for the SetWindowText() function.
Here is a reference for using basic windows functions in the DOS environment.
Ye' have the useMoney() function prototyped to accept a float deposit and a float withdrawal. Both of these variables you have declared inside the main() function on line #60; however, ye' did not pass these vars into the function.
Solution:
change line #70 to accept your balance and withdrawal vars by reference.
String is a class object. It contains it's own member variables and functions. Some common (and very handy) string class include (but not limited to) size(), length(), empty(), clear(), compare() and c_str(). String class objects also have overloaded operators, such as [], (), += and = .
Cstrings, or 'character arrays' are basically remnants of the ol' days of C. They are not nearly used as often as string class objects; however, string class objects are still backwards compatible with cstrings via use of the c_str() member.
The <cstring> library also has a whole bunch of functions that can help you use character arrays more efficiently, but they will never be as robust as a <string> object.
Sometimes you are forced to use cstrings, when you'd really want to use strings. For example, if your program handles command-line arguments, you'd have to perform cstring operations... so it pays off to be equally good at using both cstrings and strings.
Here is a list of <string> class members. Here is a list of <cstring> functions.
So what are ye' trying to do with this code? (why doesn't it work the way you think it should)
one recommendation i would make.. you have several lines of beep(900,100). i would advise creating two int's that will hold these values. for example:
//instead of
beep(900,200);
//try
int frequency = 900;
int duration = 200;
beep(frequency, duration);
that way after you got your program up and running.. and you want to tweak its performance, all you have to do is change the value of two variables instead of editing hundreds of lines of code.
perhaps computer programming isn't the field for you. perhaps you should change your major to liberal arts or something.
if pseudorandom21 is correct, perhaps having random access to the file data would be an alternative to having to read in the entire file at once.
the thing giving me trouble at the moment is how to read and store a floating point number within a struct, the data specifically for the mark is on 1 line of a text file seperated by white space.
Since ye' data is white space delimited, ye' can simply use the overloaded >> extraction operator provided by the <fstream> library:
ifstream infile;
int record = 0;
int index = 0;
infile.open("text.txt");
if(!infile.is_open())
{
cout << "\aError, file not found.";
cout << "\nFile may have been moved, renamed, or deleted...";
exit(1);
}
while(infile && record < MAX)
{
//Get marks
while(infile >> student[record].marks[index] && index < 12)
{
index++;
}
index = 0;
//Get family name
infile >> student[record].familyName;
//Get given name
infile >> student[record].givenName;
//Get computer login
infile >> student[record].computerLogin;
//advance to the next student record
record++;
}
infile.close();
This is all based on the assumption that your text file maintains a standard format that is shown in your example. This is most of the work done for you. See if you can handle and display the data on your own.
learning c++ in 24 hours would be like trying to learn women in 24 hours.
this will create 12 "computer" objects and open 12 .txt files:
ifstream computers[12];
for(int i=1; i<13; i++)
{
string file("comp");
file += itoa(i);
file += ".txt";
computers[i].open(file.c_str());
if(!computers[i].is_open())
{
cout << "\a\nError, file #" << i << " unable to be opened!";
cout << "\nFile may be been moved, renamed, or deleted. \n\n";
cout << "\nPress [Enter] to continue...";
cin.get();
}
file.clear();
}
all you have to do is load each computer object with data.
I believe <fstream.h> is either non-standard or an antiquated header for c++ (i think it's a C header); in which case, would make your instructor incorrect. Sometimes the real education occurs when you have to prove your instructor wrong.
According to wikipedia, the use of ".h" header files is depreciated: http://en.wikipedia.org/wiki/C%2B%2B_Standard_Library
It seems that you are trying to count the number of letters in a document:
if(letter_counter <= 'z' && letter_counter >= 'A') //|45|error: ISO C++ forbids comparison between pointer and integer| { letters++; }//if
This is actually not a bad attempt at accomplishing what ye' wish to do. If your compiler doesn't like this comparison, you can actually use the ascii values for 'z' and 'A', which are 122 and 65, but if you look at the ascii table, there are other values in between 'z' and 'A', like: ':', ';', '<', '=', '>', etc...
So, one solution would involve the isalpha() function from cctype:
#include<cctype>
//char letter_counter[2] can only hold two characters..!
//let's use a more flexible data type
string line_of_text; // <--can hold an entire line of data
//These loops will read in the file, line by line
//and count the number of letters
int i=0,
size = 0;
while(getline(infile, line_of_text))
{
size = line_of_text.size();
do{
if(isalpha(line_of_text[i]))
{
letter_counter++;
}
i++;
}while(i < size);
i=0;
}
Write a C program...
I don't go to a java website asking for c++ help. Why do you come to a c++ forum asking for C help.
I just don't understand why this is such a common occurance.
I'll show you what I'd do, maybe it will give ye' some ideas on how to handle ye' problem:
1. Get a sentence to translate from the user
#include<sstream>
#include<string>
#include<iostream>
#include<cctype>
cout << "Enter sentence to translate to pig latin: ";
cin >> user_input;
2. Parse the sentence into individual substrings
stringstream sentence;
string words[20];
int word_counter = 0;
//load the stringstream object with the sentence
sentence << user_input;
while(sentence)
{
words[word_counter] << sentence; //Parsing is 'white space' delimited
word_counter++;
}
3. Test each word and handle it accordingly
int i=0;
while(i < word_counter)
{
if(vowel(words[i][0])) //Test first letter of each word
{
words[i] += "way"; //Append string to end of word
}
/*
Perform all the other tests whilst inside this loop
Modify each word as necessary according to pig latin rules
*/
i++; //Increment to next word
}
opefullyhay histay elpshay.
I've never actually used the stdafx.h pre-compiled header personally; however, i did a wikipedia search for this header and found some information:
Common Implementations
stdafx.h
stdafx.h is a file, generated by Microsoft Visual Studio IDE wizards, that describes both standard system and project specific include files that are used frequently but hardly ever change.
Compatible compilers (for example, Visual C++ 6.0 and newer) will pre-compile this file to reduce overall compile times. Visual C++ will not compile anything before the #include "stdafx.h" in the source file, unless the compile option /Yu'stdafx.h' is unchecked (by default); it assumes all code in the source up to and including that line is already compiled.
The AFX in stdafx.h stands for Application Framework eXtensions. AFX was the original abbreviation for the Microsoft Foundation Classes (MFC). Optionally, Visual Studio projects may avoid pre-compiled headers, as well as they may specify an alternative name (though stdafx.h is used by default).
In my opinion, I believe your code will work fine without "stdafx.h"