I've just realized that I've never learned to read strings from file, so I did a little messing around to figure it out, but I'm having a problem with my compiler.
For my programming class I use visual c++ 2010 because it is required and it hasn't given me much problem so I haven't switched to any other.
Anyways heres my code and my problem.
It is basically supposed to read in full names from a file and store them in an array.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
const int maxsize = 100;
string friendArray[maxsize];
ifstream friends;
friends.open("myFriends.dat");
int sub = 0;
while (friendArray[sub] <= 100)
{
getline(friends, friendArray[sub]);
sub++;
}
}
in my while loop, I am recieving: error: no operator "<=" matches these operands.
I'm getting the same thing with any other operators I use also.
Any help?
You want this instead:
while (sub < 100)
Originally, you were comparing a string to an integer literal. You obviously can't do that.
Note that I also changed the <= to < otherwise, you'll be overrunning the array.
Related
#include<iostream>
#include<stack>
#include<cmath>
using namespace std;
int Narsic(stack<int> stk)
{
int x=0;
int temp=0;
int val=0;
int power_count = stk.size();
while(! stk.empty())
{
x = stk.top();
stk.pop();
temp = pow(x,power_count);
val = val + temp;
}
cout<<val;
}
int main()
{
int num,indic;
num = 1652;
stack<int> numstack;
while(num>0)
{
indic = num%10;
num = num/10;
numstack.push(indic);
}
Narsic(numstack);
return 0;
}
Basically this program is to find the Narcissistic value of a given integer, my codes can be successfully executed and it is correct, but somehow, i think , maybe it is a bit lengthy, so the purpose of posting this problem is, whether anyone can give me suggestions on how to improve the codes above?
Sorry , I'm a beginner and just started learning C++. I hope this community won't get furious against by sucky codes XD.
(Oh yeah, i do search for some codes online and implement them partially here, so if anyone saw similar codes, please be aware that i have made changes, sorry if this irritates you.)
It looks like you're largely asking about style. I'm going to take your code and edit it to be more in keeping with what I would do, then I'll comment below.
#include <iostream>
#include <stack>
#include <cmath>
using std::cout;
using std::endl;
using std::stack;
/**
* Return the Narcissistic value of the digits stored in the stack.
* A Narcissistic value is (insert description).
*/
int narsic(stack<int> stk)
{
int result = 0;
int power_count = stk.size();
while (! stk.empty() ) {
int digit = stk.top();
stk.pop();
result += pow(digit, power_count);
}
return result;
}
/**
* Entry point.
*/
int main() {
int num;
num = 1652;
stack<int> numstack;
while (num>0)
{
int indic = num % 10;
num /= 10;
numstack.push(indic);
}
int result = narsic(numstack);
cout << "Result: " << result << endl;
return 0;
}
I use Java's naming conventions. Class names begin with an upper case letter. Variables and methods begin with lower case letters. This isn't necessarily the C++ way of doing it, but I programmed Java a long time, and it's what I prefer. You'll want to find a style for your academic work, and then use whatever your future employer uses.
I prefer more whitespace to make code readable -- especially for myself. I'm nearly 60 years old, with old eyes, and as code runs all together, it gets harder and harder to read. I've added whitespace here and there.
A blanket using namespace std is considered dangerous, but I don't like sticking std:: all over the place, so I tend to add specific using statements, although not too many.
You were missing a return statement in narsic().
And you had an unusual indentation style. Old-school C/C++ is either 4 spaces or use a tab, but set your editor to 4-space tabs. You indented the braces and then indented again. That would be odd. Some people put the open brace on the same line (I moved them) and some on the next line the way you did. I actually will put them on the next line if it makes the code more readable -- like if there's an obnoxiously long and complicated if-clause.
I moved variable declaration to just as the variables were about to used. This is better for a variety of reasons, including one less initialization plus makes your code smaller. Plus, it keeps scoping rules much tighter.
I switched a num = num / 10 to num /= 10. Similar thing with result +=.
I don't like the variable name val. I changed to result. I think I might have made one or two other variables more descriptive, too.
I added function comments and I did it in the doxygen style. Commenting each method means tools can auto-generate documentation. It also helps break code up a little bit better visually. For comments, it's important to provide information not in the code. The comment for main is trivial, but having it still helps if you actually use a documentation generator -and- provides a visual break.
A change I did NOT make but would normally do: I prefer main to be the first method in my files (at the top), so I would have made a forward reference to narsic() and moved it below main. I didn't do that just because I wanted to keep the code in the same order you had it.
I moved the cout statement and included an endl.
im a new problem solver. recently i came across this problem on codeforces website. i managed to get the two values required for each turn depending on the number of turn given by the user, but i cant find the highest number of passenger at stop out of all.
#include <iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
int turn,get_off,get_on,total_passenger,highest_total;
cin>>turn;
int* stops=new int(turn);
for(int i=0;i<turn;i++){
cin>>get_off>>get_on;
total_passenger=get_on-get_off;
stops[i]=total_passenger;
}
for(int i=0;i<turn;i++){
if(stops[i]>stops[i+1]){
highest_total=stops[i];
}
}
cout<<highest_total<<endl;
return 0;
}
you can try using https://en.cppreference.com/w/cpp/algorithm/max_element
also you set the total passengers number to the difference between get off and get on and I think you should just add that difference, and to allocate memory for int* you use [] instead of ()
#include <iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
int turn,get_off,get_on,total_passenger,highest_total;
cin>>turn;
int* stops=new int[turn];
for(int i=0;i<turn;i++){
cin>>get_off>>get_on;
total_passenger+=get_on-get_off;
stops[i]=total_passenger;
}
cout<<std::max_element(stops, stops + turn)<<endl;
}
The issue seems to be with int *stops = new int(turn). It will allocate memory for 1 integer.
Use int stops[turn] and your algorithm need to be modified.
stop[i] += total_passenger need to be used with some if-else.
You can initiate stops as an array I guess(int stops[turn]) as C++ now offers to allocate memory this way even inside any function. That may solve your problem.
Alongside you will have to check corner cases as your highest_total variable may provide garbage value. So while declaring the variable assign a value to it. I prefer initializing int highest_total=-1 here.
Actually you dont need an array or pointer here. This can be solved this way-
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
int turn,get_off,get_on,total_passenger=0;
cin>>turn;
int highest_total=-1;
for(int i=0;i<turn;i++){
cin>>get_off>>get_on;
total_passenger=total_passenger+get_on-get_off;
if(total_passenger>highest_total)
highest_total=total_passenger;
}
cout<<highest_total<<endl;
return 0;
}
Firstly: int* stops=new int(turn); initializes a pointer to a new int with the value turn. See int a = 0 and int a(0) differences
Instead you should either use int* stops=new int[turn];, read about when you should use new here: When should I use the new keyword in C++?. An important note is that you have to delete the variable in order to avoid a Memory leak.
Or (which I would say is the case you should use in this scenario), int stops[turn];.
Besides that I can not argue with your logic since I believe this is not a forum to help you solve code, although the syntax seems correct.
I would recommend reading Why is "using namespace std;" considered bad practice? if you are interested in learning C++ though.
#include <iostream>
#include <stdlib.h>
#include <cstring>
using namespace std;
int main()
{
string ID[]={"620301025123"}; //ID array
long long int IC[10]={0}; //IC array
// loop to change the ID string to Array IC. I will want to increase the size
// of ID array, later on, to put in new data but for now, I'm just using one data
// which is "620301025123" first.
for(int i = 0; i < 10; ++i){
IC[i]= {atoll(ID[i].c_str())};
}
}
The error I got is:
14 29 C:\Users\ASUS\Desktop\Assign1\Untitled3.cpp [Warning] extended initializer lists only available with -std=c++11 or -std=gnu++11*/
First of all: it's #include <cstdlib> in C++.
Then, your problem does not seem to be the conversion to long long, but the initialization of the string, at least that's what the warning (not an error) says. You are using extended initializer lists, which are C++11, but haven't activated C++11 support.
The warning tells you how to activate it.
And finally: Don't get in the habit of using using namespace, at least not globally. You can use using on specific symbols, but even this I'd only do locally, and never globally.
I've Googled, asked my classmates, and finally asked my professor about this particular problem, but I haven't achieved a solution yet. I'm hoping someone here can help me out.
Basically, I need to make an array of structs that will contain 4 pieces of information per struct: country name, country population, country area, and country density. This information will be written to the structs in the array from a .txt document. This info will then be written onto the console from said array.
Unfortunately, in attempting to write anything to the structs in the array, I get 2 errors. "Cannot convert from 'const char[8]' to 'char [30]'" and "no operator '[]' matches these operands, operand types are: CountryStats [int]". These errors both refer to the line:
countries[0].countryName = "A";
Keep in mind that I have only started to use structs and this is the first time I've used them in an array. Also, I must use an array, as opposed to a vector.
Here's my code:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
struct CountryStats;
void initArray(CountryStats *countries);
const int MAXRECORDS = 100;
const int MAXNAMELENGTH = 30;
struct CountryStats
{
char countryName[MAXNAMELENGTH];
int population;
int area;
double density;
};
// All code beneath this line has been giving me trouble. I need to easily edit the
// struct variables and then read them.
int main(void)
{
CountryStats countries[MAXRECORDS];
initArray(*countries);
}
void initArray(CountryStats countries)
{
countries[0].countryName = "A";
}
As of now I am just attempting to figure out how to write information to a struct within the array and then read the information off of it onto the console. Everything else should fall into place after I find the solution to this.
Oh, and one final note: I have not quite learned the function of pointers (*) yet. I am still relatively new to C++ as my past programming education has been primarily in Java. Any and all inclusions of pointers in this code have been influenced by my classmates and professor in the pursuit of solving this problem.
Thanks in advance!
Two problems
void initArray(CountryStats countries)
must be:
void initArray(CountryStats *countries)
And you must use strcpy to copy c style string. (but i suggest to use c++ string instead of char[])
strcpy(countries[0].countryName,"A");
But I say again, use c++ features like vector<> and string.
You are not defining a definition for:
void initArray(CountryStats *countries);
but for:
void initArray(CountryStats countries);
in which countries is not an array. Since no operator[] is defined for CountryStats, the expression countries[0] fails to compile.
Since you cannot use std::vector (for some weird reasons), I'd suggest you to use an std::array:
template<std::size_t N>
void initArray(std::array<CountryStats, N>& ref) {
for (std::size_t i = 0; i < N; i++)
// initialize ref[i]
}
Of course, if you feel masochist, you can also use a C-style array:
void initArray(CountryStats* arr, int size) {
for (int i = 0; i < size; i++)
// initialize arr[i]
}
But you'll, probably, need to provide the dimension of the array as a second parameter.
This question already has answers here:
Passing a 2D array to a C++ function
(18 answers)
Closed 9 years ago.
I wrote a little programm and I can't pass two-dimensional array words[10][max_row_size] to function notify. Please help me if you can. a part of code attached.
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string.h>
#include <unistd.h>
using namespace std;
#define max_row_size 100
int notify(char words[max_row_size]);
int main(void) {
ifstream dictionary("dictionary.txt");
//ditrionary looks like
//hello-world
//universe-infinity
//filename-clock
string s;
int i=0;
char words[10][max_row_size];
while(!dictionary.eof()){
dictionary>>s;
strcpy(words[i++],s.c_str());
}
notify(words[max_row_size]);
return 0;
}
int notify(char words[max_row_size]){
cout<<words[1];
return 0;
}
It is a full code of my programm, may be it can help you
It is an errors
/home/rem/projects/github/notify_words/notify_words.cpp: В функции «int notify(int, char*)»:
/home/rem/projects/github/notify_words/notify_words.cpp:65:113: предупреждение: format «%s» expects argument of type «char*», but argument 3 has type «int» [-Wformat]
You pass words on its own: char** words is the argument in the function: i.e.
int notify(char** words){...
Easiest way for 2 dimensional array (obviously, you can typedef your array):
int notify(std::array<std::array<char, max_row_size>, 10>& words){
std::cout << words[1];
return 0;
}
Easiest for an array of strings:
int notify(std::array<std::array<std::string>, 10>& words){
std::cout << words[1];
return 0;
}
This way prevents that the array is decayed to a pointer in the function, so the size is still known.
notify(char words[][max_row_size])
to pass the whole array down
then use notify(words); to call the method
But really you should be using standard containers instead of arrays
I'm guessing you want notify to print just one word, so you need to change notify to
int notify(char* word){
cout<<word;
return 0;
}
But also the way you're calling notify will probably not produce the results you're after.
notify(words[max_row_size]);
Will try to get you the 100th word out of 10. Which will probably cause a crash.
You probably want to place notify last in your while loop and call it like this
notify(words[i]);
Also, if you have more than 10 words in your dictionary, you're in trouble. You might want to try a vector instead of an array (because vectors can grow dynamically).