Why would 'string' become an ineligible variable if I comment out Newline - c++

Complete newbie here and I had a quick question with regards to newline in my code. So I understand that inserting the using namespace std is bad practice and in writing my program I avoided using cout and cin without the adding the std:: portion first. But I figured since I'm not importing the namespace library I could just comment it out. But when I did this my string name for the variables became unrecognized (red lines underneath it). The red lines disappear when I allow namespace to be imported again. Is the variable string only available in the namespace library?
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
//using namespace std;
// read and compare names
int main()
{
std::cout << "Please enter two names \n";
string first;
string second;
std:: cin >> first >> second; // read two strings
if (first == second) std::cout << "that's the same name twice! \n";
if (first < second) std::cout << first << " is alphabetically before "
<< second << '\n';
if (first > second) std::cout << first << " is alphabetically after " <<
second << '\n';
return 0;
}

If you don't include using namespace std then you will need to say
std::string first;
std::string second;
because string is defined in the standard namespace also (as well as cout etc).
So yes you are right that string is only defined in standard. string is an object (not a primitive type) and it is this that allows you to do the if(first==second) comparison. Otherwise the "normal" way to compare string is using strcmp() or similar.

Related

I am just trying to use the getline function as an absolute beginner. I still dont know what went wrong here

#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
constexpr auto MAX_NUM_LEN = 10;
int main() {
string a_num[MAX_NUM_LEN];
cout << "Type your full ID" << endl;
cin.getline(a_num, MAX_NUM_LEN, '.');
cout << "\nyour input is: " << a_num;
}
Link to my embedded image of the program i did in VS code
[1]: https://i.stack.imgur.com/TM7BC.jpg
Use char a_num[MAX_NUM_LEN]; instead of string a_num[MAX_NUM_LEN];
Your code will run.
when you use cin.getline() function, then its first parameters would be either a constant character pointer or a character array name.
Please check following resources to learn more about getline
std::getline (string)
getline (string) in C++
C++ program to read string using cin.getline()
std::cin.getline( ) vs. std::cin

C++ script behaving badly when using "string" data type

I just want to write a simple script that asks for someone's name and prints it out. But for some reason, when I use the string data type it just kind of, does nothing.
Here is the code and output if I use a string:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
cout << "Please give me your name: ";
getline(cin, name);
cout << "Hello " << name << endl;
return 0;
}
As you can see, it just runs the .exe and nothing happens. However if I take the C approach to strings and use a character array and also don't use getline(), it works fine (but doesn't skip the '\0' character):
#include <iostream>
#include <string>
using namespace std;
int main()
{
//string name;
char name[15];
cout << "Please give me your name: ";
//getline(cin, name);
cin >> name;
cout << "Hello " << name << endl;
return 0;
}
I have tried a few other approaches and all have worked fine. For some reason, making the variable name as a string data type makes it behave weirdly. I tried looking around some C++ based books and the web but no one seems to have
had this problem.
I'm just going to add this for clarification, I checked to see if the program was just executing too fast for me to see what was going on. It is not doing that, it even skips the part where it is supposed to wait for input.
I am using Visual Studio Code to write the programs and MinGW to compile. I took my code and ran it over at https://www.onlinegdb.com/ and it worked as expected:
Could this possibly be a Windows or Command Prompt problem?
Depending on STL implementation and OS, std::cout may be buffering data in memory. It typically does not flush buffered data to console until either:
a threshold is reached
a '\n' character is output
std::cout.flush() is called (which includes outputting std::endl, which calls flush() after writing a line break).
Try calling std::cout.flush() (directly, or via std::flush) after outputting the prompt and before reading the name:
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
cout << "Please give me your name: " << flush;
getline(cin, name);
cout << "Hello " << name << endl;
return 0;
}

Bjarne Stroustrup Book - Vector and For loop - won't work

I'm having difficulties with a particular piece of code I'm learning from "Programming Principles And Practice Using C++".
I can't get an output from a loop refering to a vector. Am using std_lib_facilities and stdafx because the book and MVS told me so.
#include "stdafx.h"
#include "../../std_lib_facilities.h"
int main()
{
vector<string>words;
for(string temp; cin>>temp; )
words.push_back(temp);
cout << "Number of words: " << words.size() << '\n';
}
This will produce nothing. I'll get the prompt, type in some words, then enter, then nothing.
Tried some variations I got here and from other websites as well, such as:
//here i tried the libraries the guy used in his code
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
cout << "Please enter a series of words followed by End-of-File: ";
vector<string> words;
string word;
string disliked = "Broccoli";
while (cin >> word)
words.push_back(word);
cout << "\nNumber of words: " << words.size() << endl;
// cycle through all strings in vector
for (int i = 0; i < words.size(); ++i)
{
if (words[i] != disliked)
cout << words[i] << endl;
else
cout << "BLEEP!\n";
}
return 0;
}
Still nothing.
After trying some things, by elimination I'm pretty certain the problem is with the loop-to-vector communication, because all of these work fine:
int main()
{
vector<string>words = { "hi" };
words.push_back("hello");
cout << words[1] << "\n"; // this will print hello
for (int i = 0; i < words.size();++i) {
cout << words[i] << "\n"; // this will print out all elements
// inside vector words, ( hi, hello)
}
cout << words.size();// this will print out number 2
for (string temp; cin >> temp;) {
words.push_back(temp);
}
cout << words.size();// this won't do anything after i type in some
// words; shouldn't it increase the size of the
// vector?
}
Neither will this alone:
int main()
{
vector<string>words = { "hi" };
for (string temp; cin >> temp;) {
words.push_back(temp);
}
cout << words.size();
}
What am I missing, please? Thank you in advance.
Input the strings and when done press Ctrl+Z (followed by Enter) if on Windows or Ctrl+D if on Linux. When you do that the cin>>temp; condition inside your for loop will evaluate to false and your program will exit the loop.
Firstly, it is not necessary to use the std_lib_facilities.h. That is just something used in the book to avoid having every example in the book regularly include a set of standard headers, or to correct for non-standard behaviours between compilers. It is also a header that that does using namespace std - you will find numerous examples (both on SO and the wider internet) explaining why it is VERY poor practice to have using namespace std in a header file.
Second, it is not necessary to use stdafx.h either. That is something generated by Microsoft IDE, and provides a means of speeding up compilation in large projects, because of how it causes the compiler to work with precompiled headers. If you only expect to use Microsoft compilers, then feel free to fill your boots and use this one. However, it is not standard C++, may (depending on IDE and project settings) include windows specific headers that will not work with non-Microsoft compilers, and in forums will probably discourage people who use other compilers from helping you - since they will have good reason to assume your code uses Microsoft-specific extensions, which will mean they probably can't help you.
The first sample of code can be rewritten, in standard C++ (without use of either header above) as
#include <vector> // for std::vector
#include <string> // for std::string
#include <iostream> // std::cout and other I/O facilities
int main()
{
std::vector<std::string> words;
for(std::string temp; std::cin >> temp; )
words.push_back(temp);
std::cout << "Number of words: " << words.size() << '\n';
}
Before you get excited, this will exhibit the same problem (not apparently finishing). The reason is actually the termination condition of the loop - std::cin >> temp will only terminate the loop if end of file or some other error is encountered in the stream.
So, if you type
The cow jumped over the moon
std::cin will continue to wait for input. It is generally necessary for the USER to trigger and end of file condition. Under windows, this requires the user to enter CTRL-Z on an empty line followed by the enter key.
An alternative would be to have some pre-agreed text that cause the loop to exit, such as
#include <vector> // for std::vector
#include <string> // for std::string
#include <iostream> // std::cout and other I/O facilities
int main()
{
std::vector<std::string> words;
for(std::string temp; std::cin >> temp && temp != "zzz"; )
words.push_back(temp);
std::cout << "Number of words: " << words.size() << '\n';
}
which will cause the program to exit when the input contains the word zzz. For example
The cow jumped over the moon zzz
There are other techniques, such as reading one character at a time, and stopping when the user enters two consecutive newlines. That requires your code to interpret every character, and decide what constitutes a word. I'll leave that as an exercise.
Note there is no means in standard C++ to directly read keystrokes - the problems above are related to how standard streams work, and interact with the host system.
The user can also use the program "as is" by placing the same text into an actual file, and (when the program is run) redirect input for your program to come from that file. For example your_executable < filename.

No match for 'operator>>'

I can't figure out why it says this. I am new as you can probably tell... here is the code:
#include <iostream>
using namespace std
int main() {
if (cin >> "hi"
cout << "hello"
return 0;
}
"The thing you were using" (read: your compiler) wanted you to end your using namespace std statement with a semicolon, not to dump one at the start of a function definition.
Your code has a number of extreme and baffling syntax errors, to the extent that it's not even clear what you're trying to accomplish.
Below is a hint to get you started but, from now on, I strongly recommend that you read a good, peer-reviewed C++ book and learn the language before asking any further questions about nonsense code!
#include <iostream>
#include <string>
using namespace std;
int main()
{
string input;
getline(cin, input);
if (input == "hi") {
cout << "hello" << endl;
}
return 0;
}

Unusual/Wrong Behavior of C++ Program

My code is intended to tell the user whether the string entered is a keyword in c++.
I am reading the keywords from a file into a set and then checking if the user supplied string is in it.
#include <iostream>
#include <string>
#include <set>
#include <algorithm>
#include <fstream>
using namespace std;
int main()
{
set<string> key;
fstream fs;
string b;
fs.open("keywords.txt",fstream::in);
while(getline(fs,b))
key.insert(b);
b.clear();
for(auto x:key)
cout << x << endl;
cout << "Enter String user\nPress exit to terminate\n";
while(getline(cin,b))
{
if(b == "exit")
break;
if(key.find(b) != key.end())
cout << "This is a keyword\n";
else
cout << "This is a not a keyword\n";
b.clear();
}
fs.close();
}
The keywords.txt file is just a list of keywords and can be obtained from here
The problem is that my program reads all keywords correctly but for some of them such as false,public it cannot find them in the set.
i.e. when I enter false as user input
it says, "This is not a keyword."
Considering your input file, I think you have some keyword names with trailing spaces.
"catch "
"false "
You can trim the strings before inserting in the set to remove spaces, using boost::trim or your own trim (see this question for instance.)
(If you want some advice as for your code:
You can use std::ifstream like this for input file streams:
std::ifstream file( "keywords.txt" );
You do not need to call .close() at then of the scope, it will be done automatically thanks to RAII.
You should not reuse the same std::string objects for every purpose, you can declare new string objects close to their use. You should give them better names like "line" instead of "b". Doing this, you don't need to call ".clear()" for your strings.
Every line has just one word, you could use while(fs>>b) the >> will ignore the spaces (from moldbinlo & wangxf comments)
)