How does visual studio read instructions from code? - visual-c++

Hi there StackOverflow community. I’ve faced a certain issue in understanding how visual studio processes the ‘instructions’ given by the code.
the code I’ve written was giving me a problem when i was running it.
It went something like:
whats your guess?
donkey
whats your guess?
donkey
your guess was: donkey
whats your guess?
dog
whats your guess?
dog
your guess was: dog.
It works correctly on alternative tries.
However, if i were to remove ' GetGuess();' on line 38. everything works perfectly fine.
However, it just bothers me that the Getguess on line 38 is nt require because the thought im having right now is that it has to process Getguess first before it processes giving back the guess.
Thank you
code:
#include <iostream>;
#include <string>;
using namespace std;
void PrintIntro();
void play_game();
string GetGuess();
// entry point for out application
int main()
{
PrintIntro();
play_game();
}
//intro game
void PrintIntro()
{
constexpr int WORD_LENGTH = 5;
cout << "welcome to bulls and cows\n";
cout << "can you guess the " << WORD_LENGTH << " letters word?\n";
return ;
}
void play_game()
{
// loop for number of turns asking for guesses
constexpr int number_of_turn = 5;
for (int count = 1; count <= number_of_turn; count++)
{
GetGuess();
string guess = GetGuess();
cout << "your guess was:" << guess << endl;
}
}
//gut guess from player
string GetGuess()
{
// ask for a guess
cout << "whats your guess?\n";
string guess = "";
getline(cin, guess);
return guess;
}

A piece of advice: When you run the code please put breakpoints, especially if you want to know how your code run.
"It works correctly on alternative tries. However, if i were to remove ' GetGuess();' on line 38. everything works perfectly fine. However, it just bothers me that the Getguess on line 38 is nt require because the thought im having right now is that it has to process Getguess first before it processes giving back the guess."
To answer your question, first your must know that, when you call "string guess = GetGuess();" the compiler already retrieve the return value and store it into "guess" (in this case, the function return guess), therefore you don't have to add GetGuess() anymore (this is redundant). Your thinking that the compiler needs to "process Getguess first" is incorrect since "string guess = GetGuess();" is already processing/retrieving the return value.
Also, I think it's a good practice to initialize and declare all functions before int main() but then, it's up to how you organize all your code functions.

Related

How do I convert strings of numbers, coming from a .txt file into an int array using stoi::("string")

I've been trying to take a .txt document with three number entries, read those entries as strings and convert those entries in ints, then put them into an int array, but had no success in doing so and i have no clue as to why. Note that the entries as well as some variable names are pre determined by the assignment, additionally we have to use the std::stoi("string") command, which i am not familiar with nor has any syntax been provided to us (which is especially strange since we are usually not allowed to stray to far from the lecture material)
What I excpected to happen is that the numbers from the .txt file were converted into an array, however what actually happened is that an "unhandled exception" (my apologies if that term does not make sanes we have to programm in our native language) occured and the string library opened itself, marking the error on line 107. The problematic line in my code seems to be "auftraegearray[i++] = std::stoi(MengeanAuftraegen);"
int main()
{
std::fstream Auftraege;
Auftraege.open("Auftraege37.txt", std::ios::out);
Auftraege << "10" << std::endl;
Auftraege << "1" << std::endl;
Auftraege << "20" << std::endl;
Auftraege.close();
int i = 0;
int auftraegearray[4];
std::string MengeanAuftraegen;
Auftraege.open("Auftraege37.txt", std::ios::in);
while (!Auftraege.eof())
{
getline(Auftraege, MengeanAuftraegen);
std::cout << MengeanAuftraegen << std::endl;
auftraegearray[i++] = std::stoi(MengeanAuftraegen);
}
Auftraege.close();

C++ password program, encountering problems with spaces

#include <iostream>
#include <string>
#include <sstream> // don't mind this
#include <ctime> //don't mind this either
using namespace std;
int main() {
const string password = "hello"; //password
char word[100]; //if this were string and I put 2 words in my password it would output "invalid password" twice
do {
cin >> word;
cin.getline(word, 100);
if (word == password) { //if word is equal to password, break and move on past the loop
break;
}
cout << "Password invalid" << endl; //password not equal, it will move on to this and repeat until password is true
} while (true);
cout << "Password valid" << endl;
return 0;
}
I've been new to c++ programming for a couple months now, and I'm watching a very good course right now. In one of the tutorials he makes this password program that is present above. I've played with the program some and noticed that when I input 2 words like "example password" it would output "Invalid password" twice. I assume that is because it recognizes spaces as another input. I've made some changes so that now when I input 2 words or more it only outputs invalid password once. But now I'm facing another problem which I need help on. When I try to input the correct password, it doesn't work. What could be the answer to this mystery? Help would be appreciated and this could help me and others understand this more, and help avoid this problem in the future.
I'm glad that I already solved your problem, but let me elaborate on what I said earlier as it will be helpful for learning.
scanf("%[^\n]%*c", string );
Here the [^\n] is the scanset specifier for the scanf function, it means that the scanf function scans for characters from stdin untill it reaches a newline. This is basically a c function.
The parallel in cpp is getline(stream, char *) function, but almost all c code works in c++ hence you can use it.

string to boost::uuid conversion

I've just started using boost in c++ and I just wanted to ask a couple of questions relating to uuids.
I am loading in a file which requires I know the uuids so I can link some objects together. For this reason, I'm trying to write my own uuids but I'm not sure if there's any special conditions for the strings etc as the strings I've been using (usually something basic) are not working. Can anyone point me in the right direction? I've tried using a string generator, but to no avail thus far so I'm assuming there's something wrong with my strings (which have currently just been random words).
Here's a short example kind of thing, can't give the real code:
void loadFiles(std::string xmlFile);
void linkObjects(custObj network)
{
for (int i = 0; i < network->getLength(); i++)
{
network[i]->setId([boost::uuid]);
if (i > 0)
network[i]->addObj(network[i-1]->getId());
}
}
I took your question as "I need a sample". Here's a sample that shows
reading
writing
generating
comparing
uuids with Boost Uuid.
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/random_generator.hpp>
#include <boost/lexical_cast.hpp>
using namespace boost::uuids;
int main()
{
random_generator gen;
for (int i = 0; i < 10; ++i)
{
uuid new_one = gen(); // here's how you generate one
std::cout << "You can just print it: " << new_one << "; ";
// or assign it to a string
std::string as_text = boost::lexical_cast<std::string>(new_one);
std::cout << "as_text: '" << as_text << "'\n";
// now, read it back in:
uuid roundtrip = boost::lexical_cast<uuid>(as_text);
assert(roundtrip == new_one);
}
}
See it Live On Coliru

c++ c_str adding strange characters to the end of the string

let me first thank you for taking the time to read this.
I'm trying to read a file in c++. Currently I have a method that allows the user to select a file in explorer and returns this as an 'std::string'. I then have to open this file, but the method I have for this uses const char*. Therefore I need to convert from one to the other.
If there is an easy method in windows for reading a file using a string instead then let me know as it would solve my entire problem.
When I convert from string to const char*, using str.c_str(), I get a lot of weird characters at the end. I've researched other topics with the same problem, but the answers all seem very specific for those projects, or say just stick to sting/vector instead. Obviously I would happily do this, but I don't have a method that opens the file using a string/vector.
Any help is appreciated :) The code and output of where this occurs is pasted below.
*SOURCE
std::string f;
if (LOWORD(wParam) == 1) {
f = openFile();
char *fchar = new char[f.size()+1]; // +1 to account for \0 byte
//char *fchar = std::vector[1];
std::strncpy(fchar, f.c_str(), f.size());
file1 = fchar;
std::cout<<"string size: " << f.size() << std::endl;
std::cout<<"string: " << f << std::endl;
std::cout<<"fchar: " << fchar << std::endl;
std::cout<<"file1: " << file1 << std::endl;
}
OUTPUT
string size: 33
string: C:\Users\Joseph\Pictures\back_raw
fchar: C:\Users\Joseph\Pictures\back_raw═²²²²½½½½½½½½¯■
file1: C:\Users\Joseph\Pictures\back_raw═²²²²½½½½½½½½¯■**
std::strncpy() does not place a `\0' character at the end of the string. See http://www.cplusplus.com/reference/clibrary/cstring/strncpy/. You need to copy that as well:
std::strncpy(fchar, f.c_str(), f.size() + 1);
Where is file1 declared ?
What about openFile ? (would like to know its return type)
Could you try to manually put that '\0' ? IMHO, your char* is simply lacking the \0 at the end...
Make sure you put a \0 at the end, everywhere you need to.

Reading a value in associative array creates a new key

I have code such as this. I use
pvalueholder is class that is polymorphic , it can hold all sort of types, string..etc..
It also can have a type undefined.
typedef hash_map<pvalueholder,pvalueholder,pvaluehasher > hashtype;
hashtype h;
pvalueholder v;
v="c";
h[v]=5; // h has one element
pvalueholder v2=h[v]; // here h gets a new key/value how is that possible?
cout << (string) (h[v]) << endl; // here h gets another new key/value how is that possible?
int i =0;
for (hashtype::iterator h1=h.begin(); h1!=h.end();h1++)
{
cout << "no: " << i++ << endl;
} // this prints three lines, it should print one...
Two values are undefined here, the third one is 5 as expected.
size_t pvaluehasher::operator() (const pvalueholder& p) const
{
cout << "hashvalue:" << p.value->hashvalue() << endl;
return p.value->hashvalue();
}
returns
Here is what is printed:
hashvalue:84696444
hashvalue:84696444
hashvalue:84696444
returns:1
hashvalue:84696444
returns:1
hashvalue:84696444
returns:1
returns:1
hashvalue:84696444
Do you have any ideas what it may be?
Thank you.
Solution:
the function operator()(parameter1,parameter2) needs to be different in case of Microsoft STL.
For microsoft, it needs to return less than relationship between parameter1 and parameter2.
For gcc, it needs to return equality. I returned equality.
The comparison function for the keys was not correct...
The function returned true for equality while it has to return less than in case of Microsoft STL.
My guess would be that your hash function is incorrect - meaning it produces different hash values given the same key "c".
Show the declaration for pvalueholder and full code for pvaluehasher.
It's almost impossible to comment on hash_map, because it's never been standardized, and the existing implementations aren't entirely consistent. Worse, your code doesn't seem to be correct or compilable as it stands -- some places the value associated with the key seems to be an int, and other places a string.
Using std::tr1::unordered_map and fixing the rest of the code to compile and seem reasonable, like this:
#include <unordered_map>
#include <iostream>
#include <string>
using namespace std;
typedef std::tr1::unordered_map<std::string, int> hashtype;
std::ostream &operator<<(std::ostream &os, std::pair<std::string, int> const &d) {
return os << d.first << ": " << d.second;
}
int main() {
hashtype h;
std::string v = "c";
h[v]=5; // h has one element
int v2=h[v];
cout << h[v] << endl;
int i =0;
for (hashtype::iterator h1=h.begin(); h1!=h.end();h1++)
{
cout << *h1 << endl;
} // this prints three lines, it should print one...
return 0;
}
The output I get is:
5
c: 5
This seems quite reasonable -- we've inserted only one item, as expected.
Solution: the function operator()(parameter1,parameter2) needs to be different in case of Microsoft STL. For microsoft, it needs to return less than relationship between parameter1 and parameter2. For gcc, it needs to return equality. I returned equality. The comparison function for the keys was not correct... The function returned true for equality while it has to return less than in case of Microsoft STL.

Resources