I wanted to break the loop when the user doesn't want to add anymore:
#include<iostream>
using namespace std;
int main() {
int i = 0, a = 0, h = 0;
cout << "Enter numbers to be added:\n ";
for(i=0; ??; i++) {
cout << "\n" << h << " + ";
cin >> a;
h = h+a;
}
return 0;
}
Use std::getline to read an input line and exit the loop when the line is empty.
#include<iostream>
#include <sstream>
int main() {
int a = 0, h = 0;
std::cout << "Enter numbers to be added:\n ";
std::string line;
std::cout << "\n" << h << " + ";
while (std::getline(std::cin, line) && // input is good
line.length() > 0) // line not empty
{
std::stringstream linestr(line);
while (linestr >> a)// recommend better checking here. Look up std::strtol
{
h = h+a;
std::cout << "\n" << h << " + ";
}
}
return 0;
}
And output:
Enter numbers to be added:
0 + 1 2 3 4 5 6 7 8 9
1 +
3 +
6 +
10 +
15 +
21 +
28 +
36 +
45 +
Note that this allows multiple entries per line and looks pretty ugly, so OP is probably more interested in:
#include<iostream>
int main() {
long a = 0, h = 0;
std::cout << "Enter numbers to be added:\n ";
std::string line;
std::cout << "\n" << h << " + ";
while (std::getline(std::cin, line) && // input is good
line.length() > 0) // line not empty
{
char * endp; // will be updated with the character in line that wasn't a digit
a = std::strtol(line.c_str(), &endp, 10);
if (*endp == '\0') // if last character inspected was the end of the string
// warning: Does not catch ridiculously large numbers
{
h = h+a;
}
else
{
std::cout << "Very funny, wise guy. Try again." << std::endl;
}
std::cout << "\n" << h << " + ";
}
return 0;
}
Output
Enter numbers to be added:
0 + 1
1 + 1 2 3 4
Very funny, wise guy. Try again.
1 + 2
3 + 44444
44447 + jsdf;jasdklfjasdklf
Very funny, wise guy. Try again.
44447 + 9999999999999999999999
-2147439202 +
It is easier to use a sentinel value that you can check against, something like this:
#include<iostream>
#include<string>
using namespace std;
int main()
{
int sum = 0;
string userInput;
while(true)
{
cout<<"Enter number to be added ('q' to quit): ";
cin >> userInput;
if( (userInput == "q") || (userInput == "Q") )
{
break;
}
try
{
sum += stoi( userInput );
}
catch( const std::invalid_argument& e )
{
cerr << "Invalid input \"" << userInput << "\" received!" << endl;
return EXIT_FAILURE;
}
}
cout << "Sum: " << sum << endl;
return EXIT_SUCCESS;
}
std::getline(std::istream&, std::string&) happily gives all lines including empty lines:
#include <iostream>
#include <string>
int main() {
long long accumulator = 0;
while (true) {
// read a (possibly empty) line:
std::string buf;
if (!std::getline(std::cin, buf)) {
std::cerr << "The input stream is broken." << std::endl;
break;
}
// was the entered line empty?
if (buf.empty()) {
std::cerr << "You entered a blank line" << std::endl;
break;
}
// convert string to integer
std::size_t pos;
long long summand;
try {
summand = std::stoll(buf, &pos, 10);
} catch (std::invalid_argument &) {
std::cerr << "Not an integer: " << buf << std::endl;
continue;
} catch (std::out_of_range &) {
std::cerr << "Out of range: " << buf << std::endl;
continue;
}
if (pos != buf.size()) {
std::cerr << "Not an integer on its own: " << buf << std::endl;
continue;
}
// do something with the data:
accumulator += summand;
}
std::cout << "accumulator = " << accumulator << std::endl;
return 0;
}
Related
This is a hangman game program. I am declaring a char*p in the main which I can't understand why I am unable to delete later in the program when I don't need it. I tried it deleting later but it gives a heap memory error.
Also, I am a newbie in c++ - actually in programming - I will also appreciate if you can help me on how can I make the output of this program(on console) look more attractive and interactive. Like where should I use system("cls") commands more that can make it look more readable and remove non-essential information. Make a file in the same directory of the program with name either easy,medium or hard. so that it can have input from it when u run the program..
#pragma once
#include<iostream>
#include<string>
#include<ctime>
#include <cstdlib>
#include <stdlib.h>
#include <Windows.h>
#include<fstream>
#include<ctime>
#include <chrono> // for measuring time
using namespace std;
using namespace chrono;
//scoring the game with recard to time....
// filing : user name unique id and all that
//storing the name of user , his score, long story short, make a record of every user who passes by
int len = 0, letterCount = 0, size = 0, guesses = 6;
class tstamp
{
time_point<system_clock>tstart;
time_point<system_clock>tstop;
public:
void start()
{
tstart = system_clock::now();
}
void stop()
{
tstop = system_clock::now();
}
long long elasped()
{
return duration_cast<chrono::seconds>(tstop - tstart).count();
}
};
int checkWin(string a, char *p)
{
int count = 0;
int i = 0;
char *an = new char[a.length()];
string word = p;
for (i = 0; i < a.length(); i++)
{
if (a[i] == word[i])
count++;
}
if (count == i)
return 1; // 1 means the array is equal to the string == win
else
return 0; // not win
delete[]an; // using delete here for 1st
}
void resetData(string nameOfPlayer)
{
ofstream fout;
fout.open(nameOfPlayer + ".txt", ios::trunc);
//fout << "No Record";
fout.close();
}
void playerDetails(string nameOfPlayer, string a, bool status, float timeTaken)
{
char check = '\0';
ofstream fout;
fout.open(nameOfPlayer + ".txt", ios::app);
if (status == true)
fout << "Status : WON" << endl;
else
fout << "Status : LOST" << endl;
fout << "Word : " << a << endl;
fout << "Time taken to guess : " << timeTaken << " seconds" << endl;
fout << "********************************************";
fout << endl << endl;
fout.close();
}
string * grow(string *p, string temp) // to regrow the string array!!!!!
{
string* newArray = new string[size + 1];
for (int i = 0; i<size - 1; i++)
{
*(newArray + i) = *(p + i);
}
newArray[size - 1] = temp;
delete[] p;
return newArray;
}
char inGameMenu(char reset)
{
reset = '\0';
cout << "\n\t--->To reset your record press 'r' : ";
cout << "\n\n\t--->To display your previous record press 'd' : ";
cout << "\n\n\t--->To continue press 'x' : ";
cout << "\n\n\t--->To Exit the game press 'q' : ";
cout << endl << "\n\n\t--->Your Choice : ";
cin >> reset;
return reset;
}
string provideWord(string *contents, string a)
{
srand(time(NULL));
int i = rand() % size;
a = contents[i];
return a;
}
string* read(string fileName, string contents[])
{
string ext = ".txt";
fileName = fileName + ext;
fstream fin;
fin.open(fileName);
if (fin.is_open())
{
fin >> contents[0];
size++;
string temp;
while (fin >> temp)
{
size++;
contents = grow(contents, temp);
}
}
else
cout << "\n\tFile Not Found\n\n\n";
return contents;
}
char * makeAsterisks(string temp) // this will make astericks of the word player have to guess.
{
int len = temp.length();
char*p = new char[len];
for (int i = 0; i < len; i++)
{
p[i] = '-';
}
p[len] = '\0';
return p;
}
void displayRecord(string fileName, string display)
{
fstream fout;
fout.open(fileName + ".txt");
cout << "\n----------------------------------------------------------------------------------------------------------------";
if (fout.is_open())
{
cout << endl << endl;
while (getline(fout, display))
cout << display << endl;
}
else
cout << "\n!!No Record Found!!\nYou might be a new user\n";
cout << "\n----------------------------------------------------------------------------------------------------------------\n";
fout.close();
}
char * checkMyGuess(string word, char userGuess, char ar[])
{
bool flag = true;
for (int i = 0; i < word.length(); i++)
{
if (userGuess == word[i])
{
flag = false;
ar[i] = userGuess;
letterCount++;
}
}
if (flag == true)
{
_beep(450, 100);
cout << "\n\t!!!Wrong!!!\n";
len--;
guesses--;
}
return ar;
}
void rules()
{
system("Color 09 "); // for color effects
cout << "\n\n\t\t\t=====================\n";
cout << "\t\t\t||\tHANGMAN\t ||\n\t\t\t||\tRules\t ||"
<< "\n " << "\t\t\t=====================\n\n\n";
_beep(4000, 500);
system("Color 08 "); // for color effects
system("Color 07 "); // for color effects
cout << "\t--> Computer will think of a word and you have try\n" // rules
<< "\t to guess what it is one letter at a\n"
<< "\t time. Computer will draw a number of dashes \n "
<< "\tequivalent to the number of letters in the word.\n "
<< "\t If you suggest a letter that occurs\n "
<< "\t in the word, the computer will fill in the blank(s)\n"
<< "\t with that letter in the right place(s).\n"
<< "\t The session will be timed. \n\n";
cout << endl;
cout << "\t--> Total number of wrong choices : 6\n\n"; //wrong turns
cout << "\t--> Objective : Guess the word / phrase before you run out of choices!\n\n"; // obj
}
int checkForName(string fileName)
{
fileName = fileName + ".txt";
char line = '\0';
fstream fin;
char fromFile[7] = "\t\tName";
fin.open(fileName);
int i = 0,
check = 0;
while (fin.get(line) && i < 7)
{
if (line == fromFile[i++])
check++;
}
if (check == i - 1)
return 1;
else
return 0;
fin.close();
}
void checkForRecord(string fileName)
{
fileName = fileName + ".txt";
char line = '\0';
fstream fin;
char fromFile[7] = "No";
fin.open(fileName);
int i = 0,
check = 0;
while (fin.get(line) && i < 3)
{
if (line == fromFile[i++])
check++;
}
if (check == i - 1)
{
fin.open(fileName, ios::trunc);
fin.close();
}
fin.close();
}
int menu(int mode) // this function asks the user to enter the difficulty level of the game!!! You can't even beat medium!
{
system("cls");
cout << "Please select the Level of Game :\n";
cout << "1. Easy" << endl;
cout << "2. Medium" << endl;
cout << "3. Hard" << endl << endl;
cout << "Your Choice : ";
cin >> mode;
while (!(mode <= 3 && mode >= 1))
{
cout << endl << endl;
cout << "Please Enter the number of given choices: ";
cin >> mode;
}
return mode;
}
int comMenu(string nameOfPlayer, char reset)
{
string readData;
reset = '\0';
while (1)
{
reset = inGameMenu(reset);
if (reset == 'r')
{
resetData(nameOfPlayer);
system("cls");
Sleep(1);
}
else if (reset == 'd')
{
system("cls");
Sleep(1); // just to add a little delay!
cout << "Your Record Shows :--->\n";
displayRecord(nameOfPlayer, readData);
}
else if (reset == 'x')
break;
else if (reset == 'q')
break;
else
{
cout << "\n\n!!!Invalid Choice!!!\n\n";
}
}
return reset;
}
int main()
{
string nameOfPlayer;
char anyKey = '\0';
string name;
cout << endl;
rules();
cout << "Enter the name of player: ";
cin >> nameOfPlayer;
while (1)
{
char reset = '\0';
reset = comMenu(nameOfPlayer, reset);
if (reset != 'q') // check to exit the game
{
int uniquevar = checkForName(nameOfPlayer);
if (uniquevar != 1)
{
ofstream fout;
fout.open(nameOfPlayer + ".txt", ios::app);
fout << "\t\tName of Player : " << nameOfPlayer << endl << endl << endl;
fout.close();
}
while (1)
{
system("Color E0");
bool status = true; //initially win
size = 0,
len = 0,
letterCount = 0,
guesses = 6;
string a = ""; // it holds the word
string *contents = new string[1];
string name = "";
char b;
int mode = 0;
tstamp ts;
bool notRepeat[26] = { 0 };
if (anyKey == 'X' || anyKey == 'x')
break;
else
{
mode = menu(mode);
if (mode == 1)
name = "easy";
else if (mode == 2)
name = "medium";
else if (mode == 3)
name = "hard";
contents = read(name, contents);
cout << endl;
}
a = provideWord(contents, a);
delete[]contents;
len = a.length();
char *p = makeAsterisks(a); // detele it later
cout << "Total number of words to guesses: " << len << endl << endl;
cout << "Total guesses you have: 6\n";
cout << "Word :\n\n\t" << p << endl << endl;
ts.start(); // it starts counting the time...
while (guesses != 0)
{
cout << "Enter char: ";
cin >> b;
if (b >= '1' && b <= '9')
{
cout << "\n\nThere is not number in the given word\n\n";
continue;
}
int temp = b - 97; // it assigns the value of alphabet to temp i.e a=0,b=0 so on...
if (notRepeat[temp] != false)
{
cout << "\n\nYou've already used this word\n\n";
cout << "Remaining Choices: " << guesses << endl << endl;
continue;
}
else
{
p = checkMyGuess(a, b, p);
int checkingTheWin = checkWin(a, p);
if (checkingTheWin == 0)
{
}
else
{
cout << "\n\n\t*************You Won****************\n\n";
status = true; //true = win
break;
}
notRepeat[temp] = true;
cout << endl << endl;
cout << "Remaining Choices: " << guesses << endl;
cout << endl << '\t' << p << endl;
}
}
ts.stop();
cout << "Time Taken: " << ts.elasped() << " seconds\n\n";
p = NULL;
if (guesses == 0)
{
status = false; //false = lose
checkForRecord(nameOfPlayer);
playerDetails(nameOfPlayer, a, status, time); // right here it will create a file with the name of user
cout << "\n\nGame Over!!!\n\n";
cout << "\t\tThe word was \n\t\t\" " << a << "\"\n\n";
}
else
{
checkForRecord(nameOfPlayer);
playerDetails(nameOfPlayer, a, status, time); // right here it will create a file with the name of user
}
break;
} //ending block of while(1) first
system("color 07"); // shashka!!
}
if (reset == 'q') // to exit the game if the user decides so right away!!
break;
}
cout << "Exiting the Game\n\n";
_beep(3000, 500); // ending sound!
return 0;
}
In makeAsterisks you don't allow for the null terminator. You need to allocate one more character
char * makeAsterisks(string temp)
{
int len = temp.length();
char*p = new char[len + 1]; // <-- change here
for (int i = 0; i < len; i++)
{
p[i] = '-';
}
p[len] = '\0';
return p;
}
Now having said that, you are already using string, why not make life easier for yourself and use it everywhere? Here's makeAsterisks rewritten to use string.
string makeAsterisks(string temp)
{
return string(temp.length(), '-');
}
I am trying to work out how I would be able to implement this autokey cipher and think that I have most of it worked out. The cipher is supposed to use a subkey style system using the characters positions in the alphabet.
Currently I am stuck on how to handle a few symbols " ;:,." when they are input as part of the encryption or decryption string and and not sure how to approach it as I am new to the language. Any guidance or direction would be wonderful. Posed the code and an example of how the cipher should work below.
Cipher Description:
#include <iostream>
#include <string>
#include <assert.h>
using namespace std;
//Declares
char autokeyE(int, int);
char autokeyD(char);
char numToLetter(int);
int letterToNum(char);
int main()
{
//Declares
string inputText, finalText;
int firstAlpha = 0;
int key = 0;
int option = 0;
//First Values
do
{
cout << "What operation would you like to do? Press '1' for Encrypt and '2' for Decrypt." << endl ;
cin >> option;
if (option == 1)
{
cout << "Please input your plain text to encrypt." << endl ;
cin >> inputText;
cout << "Please input your key to encrypt with." << endl;
cin >> key;
string finalText = "";
firstAlpha = letterToNum(inputText[0]);
finalText = numToLetter((firstAlpha + key) %26);
//inputText[0] = finalText[0];
for (int x = 1; x < inputText.length(); x++)
{
finalText += autokeyE(letterToNum(inputText[x-1]), letterToNum(inputText[x]));
}
cout << finalText << endl;
}
if (option == 2)
{
cout << "Please input your encrypted text to decrypt." << endl ;
cin >> inputText;
string finalText = "";
firstAlpha = letterToNum(inputText[0]);
finalText = numToLetter((firstAlpha + key) %26);
for (int x = 1; x < inputText.length(); x++)
{
//cout << inputText[x]; Testing output
finalText += autokeyD(inputText[x]);
}
cout << finalText << endl;
}
}
while (!inputText.length() == 0);
}
char autokeyE(int c, int n)
{
cout << "Keystream: " << n << " | Current Subkey: " << c << endl;
int result = 0;
//c = toupper(c);
result = ((c + n) +26 )%26;
cout << "C as a numtoletter: " << numToLetter(result) << " Result: " << result << endl;
return numToLetter(result);
return c;
}
char autokeyD(char c)
{
//Decrypting Shift -1
if (isalpha(c))
{
c = toupper(c);
c = (((c - 65) - 1) % 26) + 65;
}
return c;
}
char numToLetter(int n)
{
assert(n >= 1 && n <= 32);
return "ABCDEFGHIJKLMNOPQRSTUVWXYZ ;:,."[n];
}
int letterToNum(char n)
{
if (isalpha(n))
{
n = toupper(n);
return(int) n - 65;
}
else
{
cout << "REUTRNING A NON ALPHA CHARACTER AS: " << n << endl;
return(int) n -30;
}
}
I don't understand your question, but I reckon the answer would be to do a back slash before each character that does not work, like so: "\;\:\,\." ( some of these may work, so only do it on the ones that don't)
You can handle symbols using isPunct in C++ such as:
if (isPunct(inputText[x]) {
//do whatever it is you need to do
}
FizzBuzz program. The user enters numbers separated by a comma. The program reads input and lets the computer know if divisible by 3, 5 or both. When the user enters 15,5,30, the program will only output the first number, 15 and stops there. What am I doing wrong?
void processVector(vector<int> intVector)
{
bool loop;
for (int i = 0; i < intVector.size(); i++)
{
loop = true;
}
}
int main()
{
cout << "Welcome to the FizzBuzz program!" << endl;
cout << "This program will check if the number you enter is divisable by
3, 5, or both." << endl;
cout << "Please enter an array of numbers separated by a comma like so,
5,10,15" << endl;
cin >> userArray;
vector<int> loadVector(string inputString);
istringstream iss(userArray);
vector <int> v;
int i;
while (iss >> i);
{
v.push_back(i);
if (iss.peek() == ',')
iss.ignore();
if (i % 15 == 0)
{
cout << "Number " << i << " - FizzBuzz!" << endl;
}
else if (i % 3 == 0)
{
cout << "Number " << i << " Fizz!" << endl;
}
else if (i % 5 == 0)
{
cout << "Number " << i << " Buzz!" << endl;
}
else
{
cout << "Number entered is not divisable by 3 or 5." << endl;
}
}
system("pause");
}
Here is how I would approach the problem:
#include <iostream>
#include <string>
#include <vector>
int main() {
std::cout << "!!!Hello World!!!" << std::endl; // prints !!!Hello World!!!
std::cout << "Please enter your numbers seperated by a comma (5, 3, 5, 98, 278, 42): ";
std::string userString;
std::getline(std::cin, userString);
std::vector<int> numberV;
size_t j = 0; // beginning of number
for(size_t i = 0; i < userString.size(); i++){
if((userString[i] == ',') || (i == userString.size() -1)){ // could also use strncmp
numberV.push_back(std::stoi(userString.substr(j, i))); // stoi stands for string to int, and .substr(start, end) creates a new string at the start location and ending at the end location
j = i + 1;
}
}
for(size_t n = 0; n < numberV.size(); n++){
std::cout << numberV[n] << std::endl;
}
return(0);
}
This should give you a method to solve the problem (without handling the fizzbuzz part of your program) that I personally find simpler.
The basic form for using functions is:
<return type> <function_name(<inputs)>{
stuff
};
So, a basic function that takes a string and returns a vector (what you are wanting) would be:
std::vector myStringToVector(std::string inputString){
std::vector V;
// your code (see the prior example for one method of doing this)
return(V);
};
It also looks like they want a separate function for outputting your vector values, this could look something like:
void myVectorPrint(std::vector inputVector){
// your code (see prior example for a method of printing out a vector)
};
Thank you #Aaron for the help. Here is the finished code and it works great!
I had to take a little more time researching a few things and trying to understand which order and what to put where in terms of the functions and how to call them. I appreciate all the help as I said I am a noob.
#include "stdafx.h"
#include <iostream>
#include<sstream>
#include<string>
#include<vector>
using namespace std;
vector<int> loadVector(string inputString)
{
stringstream ss(inputString);
vector <int> numberV;
int n;
size_t j = 0; // beginning of number
for (size_t n = 0; n < inputString.size(); n++)
{
if ((inputString[n] == ',') || (n == inputString.size() - 1))
{
numberV.push_back(std::stoi(inputString.substr(j, n)));
j = n + 1;
}
}
return numberV;
}
void processVector(vector<int> intVector)
{
for (int i = 0; i < intVector.size(); i++)
{
int n = intVector.at(i);
if (n % 15 == 0)
{
cout << "Number " << n << " - FizzBuzz!" << endl;
}
else if (n % 3 == 0)
{
cout << "Number " << n << " Fizz!" << endl;
}
else if (n % 5 == 0)
{
cout << "Number " << n << " Buzz!" << endl;
}
else
{
cout << "Number entered is not divisable by 3 or 5." << endl;
}
}
}
int main()
{
cout << "Welcome to the FizzBuzz program." << endl
<< "Please enter an array of numbers separated by comma's (5, 10, 15)"
<< endl;
string inputString;
getline(cin, inputString);
try
{
vector<int> intVector = loadVector(inputString);
processVector(intVector);
}
catch (const exception& e)
{
cout << "Exception caught: '" << e.what() << "'!;" << endl;
}
system("pause");
return 0;
}
I'm trying to store hexadecimal values into some form of an array from a file then change those numbers to binary. So far the program I wrote is only collects the last value. The file looks something like this. note(a 1 or 0 is before each hex value)
1 408ed4
0 10019d94
0 408ed8
1 10019d88
0 408edc
0 1001322
My code is #include
#include <fstream>
#include <string>
#include <cstdlib>
#include <bitset>
#include <sstream>
#define MAX_ADDRESSES 1000000
using namespace std;
int main(int argc, char **argv) {
//Declare variables
int szL1 = atoi(argv[2]);
int szL2 = atoi(argv[4]);
string type = argv[6]; //Determines the type of cache
//string fileN = argv[7];
int info, i = 1, j = 1; //info is what is read in, i & j are testing variables
string *rd_add = new string[MAX_ADDRESSES]; //set the max string length for what's read
string *wrt_add = new string[MAX_ADDRESSES]; //set the max string length for what's written
int total = 0; //total # of reads/writes
int rds = 0; //base # of reads
int wrt = 0; //base # of writes
int array_size = 1001024;
char *array = new char[array_size];
int position = 0;
ifstream fin("big_trace.txt");//open big trace file********
if (fin.is_open()){
cout << "File opened successfully" << endl;
while (!fin.eof() && position < array_size){
fin.get(array[position]);
position++;
}
array[position - 1] = '\0';
for (int x = 0; array[x] != '\0'; i++){
cout << array[i];
}
}
else{
cout << "File could not be opened" << endl;
}
//check for a power of 2 for szL1
while (1)
{
if (i == szL1)
break;
//Error Message
else if (i > szL1)
{
cout << "Error. sizeL1 must be a power of 2. Please try again." << endl << endl;
return 0;
}
i *= 2;
}
//cout << "size1 " << szL1 << endl;
//check for a power of 2 for szL2
while (1)
{
if (j == szL2)
break;
//Error
else if (j > szL2)
{
cout << "Error. sizeL2 must be a power of 2. Please try again." << endl << endl;
return 0;
}
j *= 2;
}
//cout << "size2 " << szL2 << endl;
//Check to see if szL2 is larger than szL1
if (szL2 <= szL1)
{
cout << "Error. sizeL2 must be larger than sizeL1. Please try again." << endl << endl;
return 0;
}
//Read file contents*****
while (cin >> info) //check this part
{
//If it is a 1, increment read files
if (info == 1)
{
cin >> rd_add[i++];
rds++;
}
else if (info == 0)
{
cin >> wrt_add[j++];
wrt++;
}
else
{
continue;
}
}
total = rds + wrt;
//Print the arguments read
cout << endl << "Input Parameters read:" << endl;
cout << "SizeL1: " << szL1 << endl;
cout << "SizeL2: " << szL2 << endl;
cout << "Type: " << type << endl;
//Print file stats
cout << endl << "Memory References Read from File" << endl;
cout << "Total: " << total << endl;
cout << rds << " Reads" << endl;
cout << wrt << " Writes" << endl;
return 0;
}
If you want to get only the hexadecimal values in a vector and your file is as you said you can just do it as below:
String hexValue, dummy;
Vector<String> hexValueVector;
ifstream fin("big_trace.txt");//open big trace file********
if (fin.is_open()){
cout << "File opened successfully" << endl;
while (!fin.eof()){
fin >> dummy >> hexValue;
hexValueVector.push_back(hexValue);
....//your remaining code
Do not forget to include the Vector library.
#include <vector>
Hope this will help you.
EDITED:
if you need the dummy too you have just to put both values in a structure:
struct myStructure{
String dummy;
String hexValue;
};
and instead of creating a vector of string you create a vector of myStructure:
Vector<myStructure> myStructureVector;
to fill your vector you have just to do this:
myStructure myStructure;
if(fin.is_open()){
...
while (!fin.eof()){
fin >> myStructure.dummy >> myStructure.hexValue;
myStructureVector.push_back(myStructure);
If this solves your problem, please vote for the answer.
About Vector, it is a STL container, if you want more details about it check http://www.cplusplus.com/reference/vector/vector/
So I'm trying to complete this part of a program where I have to read a text file from Stdin and add it to the 'word list' wl. I get how to read from a text file but I don't know how to go about adding 'words' to a list, if that makes sense. So here's what I got:
string getWord(){
string word;
while (cin >> word){
getline(cin, word);
}
return word;
}
void fillWordList(string source[], int &sourceLength){
ifstream in.file;
sourceLength = 50;
source[sourceLength]; ///this is the part I'm having trouble on
Source is an array that determines how many words are read from the text and length is the amount printed on screen.
Any ideas on what I should begin with?
EDIT: Here's the program I'm writing the implementation for:
#include <iostream>
#include <string>
#include <vector>
#include "ngrams.h"
void help(char * cmd) {
cout << "Usage: " << cmd << " [OPTIONS] < INPUTFILE" << endl;
cout << "Options:" << endl;
cout << " --seed RANDOMSEED" << endl;
cout << " --ngram NGRAMCOUNT" << endl;
cout << " --out OUTPUTWORDCOUNT" << endl;
}
string source[250000];
vector<string> ngram;
int main(int argc, char* argv[]) {
int n, outputN, sl;
n = 3;
outputN = 100;
for (int i = 0; i < argc; i++) {
if (string(argv[i]) == "--seed") {
srand(atoi(argv[i+1]));
} else if (string(argv[i]) == "--ngram") {
n = 1 + atoi(argv[i+1]);
} else if (string(argv[i]) == "--out") {
outputN = atoi(argv[i+1]);
} else if (string(argv[i]) == "--help") {
help(argv[0]);
return 0; }
}
fillWordList(source,sl);
cout << sl << " words found." << endl;
cout << "First word: " << source[0] << endl;
cout << "Last word: " << source[sl-1] << endl;
for (int i = 0; i < n; i++) {
ngram.push_back(source[i]);
}
cout << "Initial ngram: ";
put(ngram);
cout << endl;
for (int i = 0; i < outputN; i++) {
if (i % 10 == 0) {
cout << endl;
}
//put(ngram);
//cout << endl;
cout << ngram[0] << " ";
findAndShift(ngram, source, sl);
} }
I'm supposed to use this as a reference but it dosen't help me too much.
Declaring raw array requires the size of the array to be a compile-time constant. Use std::vector or at least std::array instead. And pass source by reference if you want to fill it.