I'm new to C++, so I'm still trying to figure out how to do basic debugging from errors printed on the terminal. I'm trying to print a pyramid of asterisks (*), but I keep getting this error that says "'string' declared here". /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/iosfwd:194:65: note:
'string' declared here
typedef basic_string, allocator > string;
^
1 error generated.
I've tried looking up how to read some of these errors in C++, but haven't been able to find a useful guide that isn't written in some alien technical gibberish. So if you could dumb down the explanation a little that would be great.
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
using namespace std;
String printAst(int number){
for(int i = 0; i < number; i++){
cout << "* ";
}
}
int main(){
printAst(3);
//***
//**
//*
return 0;
}
I have the expected print out listed in //
Here is a corrected version of your code. The immediate cause of your current errors appears to have been the String return type of the printAst() function. If you wanted to return a string, then you probably intended to use std::string, not String. But, even after fixing this, I noticed that your logic for printing the pyramid also had a problem, so I fixed that too.
void printAst (int number) {
for (int i=0; i < number; ++i) {
for (int j=0; j < number-i; ++j) {
cout << "* ";
}
cout << "\n";
}
}
int main() {
printAst(3);
return 0;
}
* * *
* *
*
The major changes I made include using a double for loop to print the inverse pyramid. The logic is that there are number levels to the pyramid, and at each level we print number count of asterisks.
Also, since printAst does not return anything, I changed the return type to void.
Related
I am working on a program that has to do with arrays. I decided that the input the user provides to be a string to later being converted to an integer once it is determined it is one. This way the program wouldn't run into an error when words/letters are entered. The issue I am having is the conversion from string to int. I want to change that because later in the program I am going to search the array for a given value and display it and its placement in the array. This is the code I have thus far:
#include <stdio.h>
#include <iostream>
using namespace std;
//check if number or string
bool check_number(string str) {
for (int i = 0; i < str.length(); i++)
if (isdigit(str[i]) == false)
return false;
return true;
}
int main()
{
const int size = 9 ;
int x, UserInput[size], findMe;
string userInput[size];
cout << "Enter "<< size <<" numbers: ";
for (int x =0; x < size; x++)
{
cin >> userInput[x];
if (check_number(userInput[x]))
{//the string is an int
}
else
{//the string is not an int
cout<<userInput[x]<< " is a string." << "Please enter a number: ";
cin >> userInput[x];}
}
int i;
for (int i =0; i < size; i++)
{
int UserInput[x] = std::stoi(userInput[x]); // error occurs here
}
for (int x= 0; x< size; x++)
{
if (UserInput = findMe)
{
cout <<"The number "<< UserInput[x] << "was found at " << x << "\n";
}
else
{
//want code to continue if the number the user is looking for isn't what is found
}
}
return 0;
}
Made comments here and there to kinda layout what I want the code to do and whatnot. I apperciate any help you can give, thank you.
This code:
int UserInput[x] = std::stoi(userInput[x]);
declares an int array of size x, to which you are assigning a single int (the result of std::stoi), which obviously doesn't work.
You need to assign an int to a particular index of the existing array, like this:
UserInput[x] = std::stoi(userInput[x]);
Given this comparison if (UserInput = findMe), which should actually be if (UserInput == findMe), it seems you want to declare a single int which stores the result of std::stoi. In that case, you should use a different name than the array, and write something like this:
int SingleUserInput = std::stoi(userInput[x]);
Also, please indent your code consistently, and compile with all your warnings turned on. Your code will be easier to read, and the compiler will point out additional problems with your code. And please don't use using namespace std;, it's a bad habit.
I don't understand why do u even need to use another loop to convert the string value to int. stdio.h header file does provides with preinstalled functions to make your work easier...
for (int x =0; x < size; x++)
{
getline(cin,userInput1[x]);
UserInput[x]=stoi(userInput1[x]);
}
stoi() function converts the string input to int, and you can call it dynamically as soon as you enter your string input,It will make you work easier and reduce the time complexity
Good night to everyone!
I am trying to compare 2 strings in c++, using the .compare() function. However, the result i see is not what is expected from this function. Take a look please.
#include <iostream>
#include <string>
using namespace std;
class game
{
private:
char mtx [2][2];
int i = 0, j = 0, a = 0;
std::string matrix1;
std::string xis = "xx";
public:
game();
char winner();
};
game::game()
{
for(i = 0; i<2; i++)
{
for (j = 0; j<2; j++)
{
mtx [i][j] = 'x';
}
}
char game::winner()
{
i = j = 0;
for (j=0; j<2; j++)
{
matrix1 = mtx [0][j]; //string recieve the first line of the matrix.
}
a = xis.compare(matrix1);
cout << a<<endl;
}
int main(void) {
velha game;
velha.winner;
}
When I compile the program the a value printed is neither a '0' nor any other integers. It prints #85.
Notes: I've also tried to use <string.h> and strncmp() using a char array instead of std:: string but with no success.
I was trying to create a game class and I did not put here the other methods because they are not relevant). (also, I use Linux Mint to code)
Can anyone help me please in this context?
#include <iostream>
#include <string>
int main(void) {
std::string first, second;
std::cout << "First String: ";
getline(std::cin, first);
std::cout << "Second Line: ";
getline(std::cin, second);
if (first == second)
std::cout << "Same strings.";
else
std::cout << "Different strings.";
return 0;
}
Explanation: Just taken two strings from the user and matches straightforward without using any much complexity, just used a conditional operation.
For string compare and even strcmp the value returned will be the lexicographical comparison of the two strings. The following are the values you should see:
negative if *this appears before the character sequence specified by the argument in lexicographical order
0 if *this and the character sequence specified are equivalent
positive if *this appears after the character sequence specified by the argument in lexicographical order
If you are looking to get the first column of your matrix, do a string comparison on, you would want to do something like:
for(int col = 0; col < 2; col++) {
matrix1.push_back(mtx[0][col]); // This appends that character to the end of your string
}
If you are looking to get the rows you can just do the following:
matrix1 = mtx[0];
// To ensure you have a null terminated string
// Otherwise you will have garbage.
matrix1.replace(matrix1.begin() + 2, matrix1.end(), 1, "\0");
I have ran through the test with comparing that the matrix contains "xx" and ended up receiving 0. However a much easier comparison is to us operator == to simply return a true or false value.
Hi I'm trying to make a program that takes a sum as an input lets say 1+2+3+2+2+1 and must sort the sum out as 1+1+2+2+2+3
this is the code
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
int main() {
string s;
char w[100];
char x[100];
cin>>s;
//moving string s to array w to remove the '+' charachter for sorting
for (int i=0; i>s.size() ;i++){
if (s.at(i) = '+')continue;
else s.at(i) == w[i];
}
//sorting array w
sort(w,w+100);
//moving array w to array x and re-adding the '+' after sorting
for (int y=0; y > s.size();y++){
w[y]==x[y];
x[y+1]=='+';
}
cout<<x;
return 0;
}
but when i run it, it gives me a blank output
this is my first time at a c++ program im still a beginner at it
thanks for the help in advance!
I can see that you are new to the language, as you lack some understanding of basic concepts. I will first give you some tips and explanation on your mistakes, then I'll give you a more suitable solution.
First of all, try avoiding using C-styled arrays like you do with w and x. They are prone to errors because of no bounds checking, look into using std::vector or std::array instead.
== and = are NOT the same! == is used when comparing two things and = is used for assigning the right side to the left side.
Your loops are completely wrong, using
for (int i=0; i>s.size() ;i++)
will never even enter the loop. Use i < s.size() of course. I also recommend using ++i instead of i++ but that is not too important.
Your "thinking in code" is sometimes weird too
for (int i=0; i>s.size() ;i++){
if (s.at(i) = '+')continue;
else s.at(i) == w[i];
}
(not minding the > and = mistakes), why not check if it is not '+' instead of continueing and then doing something?
this code should logically be
for (int i=0; i>s.size() ;i++){
if (s.at(i) != '+') s.at(i) == w[i];
}
Last but not least, try to be consistent. First you use i as loop variable and the second time you use y. Not that it matters, but consistency is always good when coding.
I made a quick solution for your problem:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
string input;
cin >> input;
vector<int> nrs = vector<int>(); //initialising this is not really needed
for (char c : input) //range based for loop, prevents mistakes with indices
{
if (c != '+')
{
nrs.push_back(c - '0'); // a char minus '0' gives the numerical value
}
}
sort(nrs.begin(), nrs.end());
string answer;
for (int nr : nrs) //range based for loop again
{
answer += to_string(nr); //use to_string to convert an int to a string
if (nr != nrs.back()) //to avoid adding the '+' after the last character
{
answer += '+';
}
}
cout << answer << endl;
return 0;
}
I am writing a very easy program for the open.kattis programming website. This is one of the easiest problems on their website so its quite a hit to my ego. When I test the code myself it works fine, but their results indicate that I get a runtime error on an unknown test case. The link to the problem description is: https://open.kattis.com/problems/everywhere but the general basis of the problem is I'm trying to determine the number of unique instances in a list of strings
My code is:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
short t; // test cases
short trips;
char city[21];
char cities[50][21];
bool found;
short count;
// read in the number of test cases
cin >> t;
// loop through each test case
for(int i=0; i<t; i++)
{
// read in the number of trips taken
cin >> trips;
// reset the count to 0
count = 0;
// loop through each trip
for(int j=0; j<trips; j++)
{
// read in the city
cin >> city;
// Linear search to determine if city has been visited
found = false;
for(int k=0; k<count; k++)
{
if(strcmp(city, cities[k]) == 0)
found = true;
}
// If city hasn't been visted, increment count and add to list
if(!found)
{
strcpy(cities[count], city);
count++;
}
}
// Output results for test case
cout << count << endl;
}
return 0;
}
You misread the description. char cities[50][21] isn't enough for this exercise:
The number of trips is at most 100 and no city name contains more than 20 characters.
Calling the number of possible cities "trips" is a little bit misleading here, but it's not the number of tests (T ≤ 50). That being said, you could improve your program a lot if you separate the concerns and actually use the C++ standard library:
#include <iostream>
#include <set> // <- Hint: those both will help you tremendously!
#include <string> // <-
int single_test_case(){
// ...
}
int main(){
int tests;
std::cin >> tests;
for(int i = 0; i < tests; ++i){
std::cout << single_test_case();
}
return 0;
}
What i'm willing to do is i wanna convert all the values of the array to their respective ASCII values and then store them in another array. My code is able to convert the character values into ASCII but it fails in storing them in another array. Please help me out.
#include <iostream>
#include <string>
using namespace std;
int main(){
char ass[10];
char name[]= "Chaitanya";
int size=sizeof(name);
for(int i=0; i<size; i++){
int p=name[i];
cout<<p<<"\n";
for(int j=0; j<size; j++){
ass[j]=p;
}
}
return 0;
}
When I try to run this program I get the following error message:
warning: variable ‘ass’ set but not used [-Wunused-but-set-variable]
Thank You!
I got the previous one. But what if i wanna print all those elements stored in ass once again. I'm using the following code and it does nothing. I'm not getting any error.
#include <iostream>
#include <string>
using namespace std;
int main(){
char ass[10];
char name[]= "Chaitanya";
int size=sizeof(name);
for(int i=0; i<size; i++){
int p=name[i];
cout<<p<<"\n";
for(int j=0; j<size; j++){
ass[j]=p;
}
}
for(int q=0; q<size; q++){
cout<<ass[q];
}
return 0;
}
Your warning is not a failure. It's just pointing out that once you store it, you never use it!
Your warning is just telling you that you aren't using the variable ass. It's not an error, but you do have a problem in your code:
int size = sizeof(name);
for (int i = 0; i < size; i++)
{
int p = name[i];
for (int j = 0; j < size; j++)
{
ass[j] = p;
}
}
The second for loop will simply overwrite each character in ass with the single character p. A nested for loop isn't needed, just assign the character from the main loop:
for (int i = 0; i < size; i++)
{
int p = name[i];
ass[i] = p;
}
Moreover, this can be facilitated through the Standard Library functions. For example:
#include <iostream>
#include <string>
int main()
{
std::string ass;
std::string name = "Chaitanya";
for (auto a : name)
{
std::cout << static_cast<int>(a);
}
ass = name;
std::cout << ass; // "Chaitanya"
warning: variable ‘ass’ set but not used [-Wunused-but-set-variable]
This warning just say that you have set the variable ass but you never use it. It is not an error at all.
As an example, try to output a value for this array and the warning will disappear:
std::cout << ass[0] << std::endl;
There is a little part on this warning here: http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html.
The warning is correct, you only set the values of ass you do not use the values set afterwards. If you added let's say a cout after the loop the warning would go away:
std::cout << ass[0] << std::endl ;
I also, don't think you need the second inner loop, if you want to print out each element of ass you could add it that after you set it. So the fix and additions print out could look like this:
for(int i=0; i<size; i++)
{
int p=name[i];
cout<<p<<"\n";
ass[i]=p;
std::cout << ass[i] << std::endl ;
}