Cout does not work on my other turbo c++ complier - c++

Hello guys i am beginner on the language c++
i was trying to run this code below on my ide"codeblocks" and it works
https://www.youtube.com/watch?v=vLnPwxZdW4Y (link for the tutorial that following )
#include <iostream>
using namespace std;
int main()
{
string charactername = "arnold";
int characterage;
characterage = 10;
cout << "Hello my name is" << charactername<< endl;
cout << "i am " << characterage << endl;
return 0;
}
this code does not work on my other compiler running on dosbox ? any ideas why ?

I suggest you stop using Turbo C++ as it is a very outdated and a discontinued compiler. However, if you don't have the option of using new compilers (I had the same issue as I studied C++ at school), you will have to make the following changes:
using namespace std; cannot be used in Turbo C++. You will have to remove that and replace #include<iostream> with #include<iostream.h>
Data-type string cannot be used in Turbo C++. You will have to declare a character array instead.
You will have to use #include<stdio.h> and the function puts(); to display the character array in case of Turbo C++. Alternatively you can use a loop-statement.
This will be your final code:
#include <iostream.h>
#include <stdio.h>
int main()
{
char charactername[] = "arnold";
int characterage;
characterage = 10;
cout << "Hello my name is ";
puts(charactername);
cout << "i am " << characterage << endl;
return 0;
}
Note: The puts(); function automatically puts the cursor on the next line. So you don't need to use endl;
Or, if you want to use a loop-statement to display the character array
#include <iostream.h>
int main()
{
char charactername[] = "arnold";
int characterage;
characterage = 10;
cout << "Hello my name is ";
int i=0;
while(charactername[i]!='\0') {
cout<<charactername[i];
i++;
}
cout<<endl;
cout << "i am " << characterage << endl;
return 0;
}
'\0' is the last element of the character array. So as long as the loop does not reach the last element, it will print the character array.
a[] = "arnold"; basically means an array is created like this: a[0]='a', a[1]='r', a[2]='n',.... a[5]='d', a[6]='\0'.
Alternatively, if you use cout << charactername; instead of the while loop, it will print the whole name. (This is only in the case of a string variable (character array), for an integer array or any other array you will need the while loop)

Related

VS code set up for c++

I am new in VS code. I wrote a C++ code like one below. but unfortunately in the terminal or output panel I cannot get both of the string and variable value. in the terminal only variable's inputted value is showing. How to fix this?
#include <bits/stdc++.h>
int main()
{
int slices;
std::cin >> slices;
std::cout << "You got " << slices << " of pizzas" << std::endl;
return 0;
}

Pointer to const variables in C++

I am just playing around to see where my current understanding of C++ behaviour ends. I wrote the following code, and got some very unexpected results.
#include <iostream>
#include <cstddef>
using namespace std;
int main()
{
const char c = 'A';
cout << c << endl;
size_t l = (size_t)(&c);
char* d = (char*)l;
*d = 'B';
cout << (size_t)d << " " << (size_t)&c << endl;
cout << *d << " " << c << endl;
}
The first line outputs 'A', as expected. On the second line, the two addresses are the same. However, the third line outputs "B A".
Obviously this is terrible code, but why didn't the value of c change (or why didn't it fail to compile?) In other words, if they both have the same address, why don't they have the same value?
My system is GCC 4.8.1 64-bit on MS Windows 7, x86, if it matters.

Sorting a sentence using arrays and strings

Sorry guys forewarning I suck at coding but have a big project and need help!
Input: A complete Sentence.
Output: The sorted order (ASCii Chart Order) of the sentence (ignore case.)
Output a histogram for the following categories:
1) Vowels
2) Consonants
3) Punctuation
4) Capital Letters
5) LowerCase Letters
I have no clue what to even do
Since you are vague in what your issue is, I recommend the following process:
Review Requirements
Always review the requirements (assignment). If there are items you don't understand or have the same understanding as your Customer (instructor), discuss them with your Customer.
Write a simple main program.
Write a simple main or "Hello World!" program to validate your IDE and other tools. Get it working before moving on. Keep it simple.
Here's an example:
#include <iostream>
#include <cstdlib> // Maybe necessary for EXIT_SUCCESS.
int main()
{
std::cout << "Hello World!\n";
return EXIT_SUCCESS;
}
Update program to input text & validate.
Add in code to perform input, validate the input and echo to the console.
#include <iostream>
#include <cstdlib> // Maybe necessary for EXIT_SUCCESS.
#include <string>
int main()
{
std::string sentence;
do
{
std::cout << "Enter a sentence: ";
std::getline(cin, sentence);
if (sentence.empty())
{
std::cout << "\nEmpty sentence, try again.\n\n"
}
} while (sentence.empty());
std::cout << "\nYou entered: " << sentence << "\n";
// Keep the console window open until Enter key is pressed.
std::cout << "\n\nPaused. Press Enter to finish.\n";
std::cin.ignore(100000, '\n');
return EXIT_SUCCESS;
}
Add functionality, one item at a time and test.
Add code for one simple requirement, compile and test.
After it works, make a backup.
Repeat until all requirements are implemented.
For ordering the string you can use standard c qsort function. For counting vowels, consonants, punctuation... you need a simple for loop.
Here is a working example:
#include <iostream.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int cmp(const void* pc1, const void* pc2)
{
if(*(char*)pc1 < *(char*)pc2) return -1;
if(*(char*)pc1 > *(char*)pc2) return 1;
return 0;
}
void main(int argc, char* argv[])
{
char pczInput[2000] = "A complete sentence.";
cout << endl << "Input: '" << pczInput << "'";
qsort(pczInput, strlen(pczInput), sizeof(char), cmp);
cout << endl << "Result: '" << pczInput << "'";
int iCapital = 0;
int iLowerCase = 0;
int iPunctuation = 0;
int iVowels = 0;
int iConsonants = 0;
for(unsigned int ui = 0; ui < strlen(pczInput); ++ui)
{
if(isupper(pczInput[ui])) ++iCapital;
if(islower(pczInput[ui])) ++iLowerCase;
if(ispunct(pczInput[ui])) ++iPunctuation;
if(strchr("aeiouAEIOU", pczInput[ui]) != NULL) ++iVowels;
if(strchr("bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ", pczInput[ui]) != NULL) ++iConsonants;
}
cout << endl << "Capital chars: " << iCapital;
cout << endl << "Lower case chars: " << iLowerCase;
cout << endl << "Punctuation chars: " << iPunctuation;
cout << endl << "Vowels chars: " << iVowels;
cout << endl << "Consonants chars: " << iConsonants;
cout << endl;
}
Note that I used C standard functions for counting capital, lower case and punctuation, and I had to use strchr function for counting vowels and consonants because such functions are missing in standard C library.
The output of the program is:
Input: 'A complete sentence.'
Result: ' .Acceeeeelmnnopstt'
Capital chars: 1
Lower case chars: 16
Punctuation chars: 1
Vowels chars: 7
Consonants chars: 10

line.find won't compile, line is not declared

I am a very novice programmer, and I am trying to understand the find functions for strings. At uni we are told to use c-strings, which is why I think that it isn't working. The problem comes when I compile, there is a compile error that line was not declared. This is my code:
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
using namespace std;
int main()
{
char test[256];
char ID[256];
cout << "\nenter ID: ";
cin.getline(ID, 256);
int index = line.find(ID);
cout << index << endl;
return 0;
}
Please help, it has become really frustrating as I need to understand this function to complete my assignment :/
You're trying to use C-style strings. But find is a member of the C++ string class. If you want to use C-style strings, use functions that operate on C style strings like strcmp, strchr, strstr, and so on.
Supposing you actually input some data into test also, then one way to do it would be:
char *found = strstr(test, ID);
if ( !found )
cout << "The ID was not found.\n";
else
cout << "The index was " << (found - test) << '\n';
Because find fuction a member function string class,You should declare a string class's object. I think you will do that like this:
string test = "This is test string";
string::size_type position;
position = test.find(ID);
if (position != test.npos){
cout << "Found: " << position << endl;
}
else{
cout << "not found ID << endl;
}

How do you append an int to a string in C++? [duplicate]

This question already has answers here:
How to concatenate a std::string and an int
(25 answers)
Closed 6 years ago.
int i = 4;
string text = "Player ";
cout << (text + i);
I'd like it to print Player 4.
The above is obviously wrong but it shows what I'm trying to do here. Is there an easy way to do this or do I have to start adding new includes?
With C++11, you can write:
#include <string> // to use std::string, std::to_string() and "+" operator acting on strings
int i = 4;
std::string text = "Player ";
text += std::to_string(i);
Well, if you use cout you can just write the integer directly to it, as in
std::cout << text << i;
The C++ way of converting all kinds of objects to strings is through string streams. If you don't have one handy, just create one.
#include <sstream>
std::ostringstream oss;
oss << text << i;
std::cout << oss.str();
Alternatively, you can just convert the integer and append it to the string.
oss << i;
text += oss.str();
Finally, the Boost libraries provide boost::lexical_cast, which wraps around the stringstream conversion with a syntax like the built-in type casts.
#include <boost/lexical_cast.hpp>
text += boost::lexical_cast<std::string>(i);
This also works the other way around, i.e. to parse strings.
printf("Player %d", i);
(Downvote my answer all you like; I still hate the C++ I/O operators.)
:-P
These work for general strings (in case you do not want to output to file/console, but store for later use or something).
boost.lexical_cast
MyStr += boost::lexical_cast<std::string>(MyInt);
String streams
//sstream.h
std::stringstream Stream;
Stream.str(MyStr);
Stream << MyInt;
MyStr = Stream.str();
// If you're using a stream (for example, cout), rather than std::string
someStream << MyInt;
For the record, you can also use a std::stringstream if you want to create the string before it's actually output.
cout << text << " " << i << endl;
Your example seems to indicate that you would like to display the a string followed by an integer, in which case:
string text = "Player: ";
int i = 4;
cout << text << i << endl;
would work fine.
But, if you're going to be storing the string places or passing it around, and doing this frequently, you may benefit from overloading the addition operator. I demonstrate this below:
#include <sstream>
#include <iostream>
using namespace std;
std::string operator+(std::string const &a, int b) {
std::ostringstream oss;
oss << a << b;
return oss.str();
}
int main() {
int i = 4;
string text = "Player: ";
cout << (text + i) << endl;
}
In fact, you can use templates to make this approach more powerful:
template <class T>
std::string operator+(std::string const &a, const T &b){
std::ostringstream oss;
oss << a << b;
return oss.str();
}
Now, as long as object b has a defined stream output, you can append it to your string (or, at least, a copy thereof).
Another possibility is Boost.Format:
#include <boost/format.hpp>
#include <iostream>
#include <string>
int main() {
int i = 4;
std::string text = "Player";
std::cout << boost::format("%1% %2%\n") % text % i;
}
Here a small working conversion/appending example, with some code I needed before.
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main(){
string str;
int i = 321;
std::stringstream ss;
ss << 123;
str = "/dev/video";
cout << str << endl;
cout << str << 456 << endl;
cout << str << i << endl;
str += ss.str();
cout << str << endl;
}
the output will be:
/dev/video
/dev/video456
/dev/video321
/dev/video123
Note that in the last two lines you save the modified string before it's actually printed out, and you could use it later if needed.
For the record, you could also use Qt's QString class:
#include <QtCore/QString>
int i = 4;
QString qs = QString("Player %1").arg(i);
std::cout << qs.toLocal8bit().constData(); // prints "Player 4"
cout << text << i;
One method here is directly printing the output if its required in your problem.
cout << text << i;
Else, one of the safest method is to use
sprintf(count, "%d", i);
And then copy it to your "text" string .
for(k = 0; *(count + k); k++)
{
text += count[k];
}
Thus, you have your required output string
For more info on sprintf, follow:
http://www.cplusplus.com/reference/cstdio/sprintf
cout << text << i;
The << operator for ostream returns a reference to the ostream, so you can just keep chaining the << operations. That is, the above is basically the same as:
cout << text;
cout << i;
cout << "Player" << i ;
cout << text << " " << i << endl;
The easiest way I could figure this out is the following..
It will work as a single string and string array.
I am considering a string array, as it is complicated (little bit same will be followed with string).
I create a array of names and append some integer and char with it to show how easy it is to append some int and chars to string, hope it helps.
length is just to measure the size of array. If you are familiar with programming then size_t is a unsigned int
#include<iostream>
#include<string>
using namespace std;
int main() {
string names[] = { "amz","Waq","Mon","Sam","Has","Shak","GBy" }; //simple array
int length = sizeof(names) / sizeof(names[0]); //give you size of array
int id;
string append[7]; //as length is 7 just for sake of storing and printing output
for (size_t i = 0; i < length; i++) {
id = rand() % 20000 + 2;
append[i] = names[i] + to_string(id);
}
for (size_t i = 0; i < length; i++) {
cout << append[i] << endl;
}
}
There are a few options, and which one you want depends on the context.
The simplest way is
std::cout << text << i;
or if you want this on a single line
std::cout << text << i << endl;
If you are writing a single threaded program and if you aren't calling this code a lot (where "a lot" is thousands of times per second) then you are done.
If you are writing a multi threaded program and more than one thread is writing to cout, then this simple code can get you into trouble. Let's assume that the library that came with your compiler made cout thread safe enough than any single call to it won't be interrupted. Now let's say that one thread is using this code to write "Player 1" and another is writing "Player 2". If you are lucky you will get the following:
Player 1
Player 2
If you are unlucky you might get something like the following
Player Player 2
1
The problem is that std::cout << text << i << endl; turns into 3 function calls. The code is equivalent to the following:
std::cout << text;
std::cout << i;
std::cout << endl;
If instead you used the C-style printf, and again your compiler provided a runtime library with reasonable thread safety (each function call is atomic) then the following code would work better:
printf("Player %d\n", i);
Being able to do something in a single function call lets the io library provide synchronization under the covers, and now your whole line of text will be atomically written.
For simple programs, std::cout is great. Throw in multithreading or other complications and the less stylish printf starts to look more attractive.
You also try concatenate player's number with std::string::push_back :
Example with your code:
int i = 4;
string text = "Player ";
text.push_back(i + '0');
cout << text;
You will see in console:
Player 4
You can use the following
int i = 4;
string text = "Player ";
text+=(i+'0');
cout << (text);
If using Windows/MFC, and need the string for more than immediate output try:
int i = 4;
CString strOutput;
strOutput.Format("Player %d", i);