Not declared in scope. Multiple errors - c++

For some reason, I keep getting a scope error. I continue to get multiple scope errors as well as.
#include<iostream.h>
#include<fstream.h>
#include<assert.h>
void ScanInFile(int ScanInValues[], int *total)
{
int i=0;
while(!cin>>&ScanInValues[i].eof()){
i++;
*total = i;
}
}
void SortFile(int DataSetValues[], int TotalValues)
{
int i, j, temp;
for(i = 0; i < (TotalValues - 1); i++){
for(j=0; j < TotalValues - i -1; j++){
if(DataSetValues[j] > DataSetValues[j+1]){
temp = DataSetValues[j];
DataSetValues[j] = DataSetValues[j+1];
DataSetValues[j+1] = temp;
}
}
}
}
int main(void)
{
int i, AmountOfValues=0;
int values[100]={ 0 };
ScanInFile(values, &AmountOfValues);
SortFile(values, AmountOfValues);
for(i=0; i < AmountOfValues; i++){
cout<<values[i];
}
cout<<endl;
return 0;
}
For some reason G++ wont compile the program. I continue to get an error for saying endl and cout, and eof are not not in the scope. Where have I gone wrong?

Those objects are declared inside std namespace. Either you prepend std:: before them(std::cout << ...) or add using namespace std; at the beginning of your cpp file.
After you fix your eof error, you also want to check for out of bound access on your array since you never check size before writing.

In addition to what Eric has said, there are more problems in your code that have yet to be pointed out. There's one in your ScanInFile function in which you wrote this line:
while (!cin >> &ScanInValues[i].eof())
This line will compile, but it will do something very different than what you expect. I'm assuming you're performing extraction on this line but want to execute these extractions while the end-of-file has not been reached. There's no need for the .eof() as the stream will analyse the stream state itself through an implicit conversion to boolean. This is done as:
while (cin >> ScanInValues[i])
I don't want to overcompilcate my explanation, but I just want to stress that this is the preferred way of performing extraction. Using !eof() as a condition for extraction is almost always the wrong way to go.

Related

How do you put a letter triangle in a file?

So this is for some homework I am working on.
I've been working on this for days now. I need to print a letter triangle,
example
a
aa
aaa
to a file I create in the code. I have gotten the triangle part down using a for loop but cannot figure out how to get it into a file. here is what I have so far.
#include <iostream>
#include <fstream>
using namespace std;
char loop()
{ for (int i = 1; i <=15; i++){
for (int j = 1; j <= i; j++){
cout << "a";
}
cout << endl;
}
}
int main()
{
ofstream week2 ("week2assignment.txt");
if (week2.is_open()){
char result = loop();
{
week2 << loop() + "\n";
}
}
week2.close();
else cout << "file wasnt created";
return 0;
}
This is my first post on here and I am in my second week of learning C++ so any help would be appreciated immensely. Thank you all in advance.
You just need to replace cout with week2 everywhere, since cout is the terminal and week2 is your file.
Given the current structure of your code, where you write to cout in a function, you'll need to pass week2 as an argument to that function to use it there.
First of all, don't build a habit of using using namespace std
std::endl will put a linebreak, but it will also flush your stream. Put easily, outputting something is a really costly (=takes a long time) action in regard to other actions. To account for this, streams are buffered and once the buffer is full it will be flushed automatically. When you use std::endl the buffer might be flushed prematurely and this will tank performance. This is of course not really an issue in this small exercise, but I think it's still good to know. You can use \n instead. Although it might not look like it, it will provide a platform independend linebreak and should virtually always be used instead of std::endl.
Then consider what your function loop should do. Right now, you said it has return type char but it's not returning something. Therefore you should correct this and specify that this function is not returning anything, but just performing an action, hence return type void.
As suggested by John Zwinck, if you pass the stream as an argument, your function becomes more powerful and works with any kind of outgoing stream (i.e. std::ostream).
We can make the function even more generic, but I'll leave it to you to understand the code (if not, feel free to post a comment for clarification). Please note also, that loop is not a descriptive name. I have no idea what loop does. Always give your functions a name that makes it clear what they are doing.
#include <iostream>
#include <fstream>
void print_letter_triangle(std::ostream& out, char c = 'a', int count = 15)
{
for( int i = 0; i < count; i++ ){
for( int j = 0; j < i; j++ )
{
out << c;
}
out << '\n';
}
}
int main()
{
// for testing purposes
print_letter_triangle(std::cout);
print_letter_triangle(std::cout, 'b');
print_letter_triangle(std::cout, 'c', 7);
std::ofstream week2("week2assignment.txt");
if( week2.is_open() )
{
print_letter_triangle(week2);
week2.close();
}
else
{
std::cout << "Error: File wasn't created.\n";
}
return 0;
}
Lastly: Try to build an early habit of how you want to format your code, positions of curly braces, spaces around operators. Right now it was a little bit inconsistent (which might as well have been caused by putting it on StackOverflow).
There are a couple more nitpicks one can offer (for example, I changed the loop to start from 0 and used the < instead of the <= operator, you can convince yourself that this does not change the number of loop iterations. However, it is common in programming languages to start from 0 (as counter-intuitive as that might be at first). Finally, since negative counting values do not make sense in this loop, one might change int to unsigned int, but I felt that might have been a little too much. Feel free to do so on your own, if you wish).
I suggest you use this code:
#include <iostream>
#include <fstream>
using namespace std;
const char* loop()
{ for (int i = 1; i <=15; i++){
for (int j = 1; j <= i; j++){
return "a";
}
return "\n";
}
}
int main()
{
ofstream week2 ("week2assignment.txt");
week2 << loop() << "\n";
return 0;
}
You must return a value from your loop() function.

why is the sort() changing my input array?

i am stuck on a problem where, after taking input of an array and sorting it and not doing any operation on it at all, the output shows a different array?
#include <bits/stdc++.h>
using namespace std;
int main() {
// your code goes here
int t;
cin>>t;
while(t--){
int n;
cin>>n;
long long int c[n],h[n],a[n];
for(int i=0;i<n;i++){
cin>>c[i];
}
for(int i=0;i<n;i++){
cin>>h[i];
}
sort(h,h+n);
for(int i=0;i<n;i++){
a[i]=0;
}
int i=0;
int begin=(i+1)-c[i];
int end = (i+1)+c[i];
int j=begin;
while(i<n){
a[j-1]++;
j++;
if(j>end){
i++;
begin=(i+1)-c[i];
end= (i+1)+c[i];
j=begin;
}
}
sort(a,a+n);
for(int i=0;i<n;i++){
cout<<h[i]<<" ";
}
}
return 0;
}
input for h[]={8,8,8,8,8}..n=5
output h[]={10,10,9,9,8}
Here is a version of your code written in reasonably decent C++. I didn't touch the loop in the middle because I have no clue what it's doing. You're using obscure variable names and no comments and doing all kinds of bizarre things with indexes and mixing them up with user input.
Now, reading indexes from user input and using them isn't bad, though in a real program you'd want to be doing lots of bounds checking on that input to make sure people weren't feeding you bad data. But doing all that stuff with such poorly named variables with no explanation is going to leave anybody looking at it scratching their head. Don't do that.
Also, avoid the use of begin and end as variable names, especially if they hold indexes. In most cases it will confuse things terribly as begin and end are important identifiers in the standard library and always refer to iterators, which are sort of like indexes, but most definitely not indexes, adding greatly to the confusion. beginidx and endidx could be acceptable substitutes in this case.
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
using ::std::vector;
using ::std::sort;
using ::std::copy_n;
using ::std::copy;
using ::std::fill;
using ::std::istream_iterator;
using ::std::ostream_iterator;
using ::std::cin;
using ::std::cout;
int main() {
// your code goes here
using vec_el_t = long long int;
int t;
cin >> t;
while (t--) {
int const n = []() { int n; cin >> n; return n; }();
vector<vec_el_t> c{n}, h{n}, a{n};
copy_n(istream_iterator<vec_el_t>{cin}, n, c.begin());
copy_n(istream_iterator<vec_el_t>{cin}, n, h.begin());
// Suggested debugging code:
// cout << "h before sort: "
// copy(h.begin(), h.end(), ostream_iterator<vec_el_t>{cout, " "});
// cout << '\n';
sort(h.begin(), h.end());
// Suggested debugging code:
// cout << "h after sort: "
// copy(h.begin(), h.end(), ostream_iterator<vec_el_t>{cout, " "});
// cout << '\n';
fill(a.begin(), a.end(), 0);
// Weird, unexplained algorithm begins here
int i = 0;
int begin = (i + 1) - c[i];
int end = (i + 1) + c[i];
int j = begin;
while (i < n) {
a[j - 1]++;
j++;
if (j > end){
i++;
begin = (i + 1) - c[i];
end = (i + 1) + c[i];
j = begin;
}
}
// Weird unexplained algorithm ends here
sort(a.begin(), a.end());
copy(h.begin(), h.end(), ostream_iterator<vec_el_t>{cout, " "});
}
return 0;
}
Changes made... Use vector not a variable length array, which isn't valid C++ anyway and will only work in g++ and clang. Don't use explicit loops if there is an algorithm that will do the job. Try to make as many things const as you can so you can make sure that the compiler catches it if you try to change things you didn't mean to change. Avoid using std; and if you want to import names from ::std import exactly the ones you need. Don't use compiler or library implementation specific header files and use the ones from the standard instead (i.e. no bits/stdc++.h).
As for your problem, I have no idea. I suspect that the index manipulation combined with looping isn't doing what you expect. If you print out the arrays before and after sorting, you will discover that sort only alters order, and not content.
As a general rule, always suspect your own code first and make absolutely sure it's correct. And if you really think it's the library code, prove it beyond a shadow of a doubt before coming here to ask why the library isn't doing what it says it does.
The complicated code I didn't touch looks rife with opportunities for out-of-bounds access, and that results in undefined behavior, which means your program might do absolutely anything in that case. You might change uses of operator [] with calls to the at function (one of the many perks of using vector) instead. That way, attempts at out-of-bounds access will throw an exception.
Within these lines you are accessing a outside its limits:
int i=0;
int begin=(i+1)-c[i]; // begin = 1 - c[0]; <<-- this could be arbitrarily small!
int end = (i+1)+c[i]; // unrelated
int j=begin; // also equal to 1-c[0]
while(i<n){
a[j-1]++; // increment a[-c[0]] which is UB unless c[0]==0
This means undefined behavior (UB), i.e., it could do nothing, it could segfault, or (what apparently happened in your case) access elements of an adjacent data structure.

Error in code while using logical operator '&&' several times in c++

I have done Following code to count X in an array. Here the compliation error which i get.
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
char s [n][n] ;
cin>>n;
char c ;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin >> c ;
if(c=='X')
{
s[i][j]='X';
}
}
}
int count=0;
for(int i=1;i<n-1;i++)
{
for(int j=1;j<n-1;j++)
{
if( s[i][j]=='X' && s[i−1][j−1] =='X' && s[i−1][j+1]=='X'&& s[i+1][j−1] =='X' && s[i+1][j+1] =='X')
count++;
}
}
cout<<count<<endl;
return 0;
}
prog.cpp: In function ‘int main()’:
prog.cpp:23:34: error: expected ‘:’ before ‘]’ token
{ if( s[i][j]=='X' && s[i?1][j?1] =='X' && s[i?1][j+1]=='X'&& s[i+1][j?1] =='X' && s[i+1][j+1] =='X')
^
There's nothing wrong with the logical ANDs in the if-statement - well, apart from being unreadable. The problem is everywhere else tbh.
using namespace std;
Try to avoid using namespaces like that. This is so that you prevent ambiguity with name collisions.
char s[n][n];
This is not valid C++. It is known as a VLA. Read more about this in this answer here. Instead, use constexpr or a dynamic array such as std::vector.
int n;
char s[n][n];
cin>>n;
Due to the fact that n is a local variable, it is defined using garbage values (193446 or -539646 or ...). This means that you may end up with a 2D array of negative spaces??? It's only after that n is being set to a number from the user input. Assuming that VLAs are not a problem, what you should do is the following:
int n = 0;
cin>>n;
char s[n][n]; //still not valid C++
Furthermore, the 2D array is initialized with garbage values.
This, I have to admit, I do not understand. If the elements of the 2D array are only set when the user input is 'X', then what values will the rest of the array have?
cin >> c ;
if(c=='X')
{
s[i][j]='X';
}
Did you just want to fill in the array with user input values? If so, then all you need is the following:
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
std::cin >> s[i][j];
And finally the program counts the X patterns where X needs to be at all four corners of another X. Apart from the fact that having long if-statements is a bad practise, the if-statement would return the correct result.
See a running version of your demo here: https://rextester.com/ASQ26945

Functions that checks the greatest common divisor of composite figures in an array

#include <iostream>
using namespace std;
int sal_sk (int sal){ // If sal is a composite figure, then true, if its not then false.
for (int i = 2; i <= sal; i++){
if(sal%i==0)
return true;}
return false;
}
int lkd(int a,int b){ // Checks the gcd
int c;
while(b > 0) {
c = b;
b = a % b;
a = c;
}
return a;
}
int main(){
int ok;
do{
int n;//Number of elements
int*a; //
int sal;
cout<<"Put in the number of elements"<<endl;
std::cin >> n;
cout<<"Input"<<n<<"elements"<<endl;
std::cin >> *a;
int *array = new int[*a];
int rez = a[0];
for(int i=1; i<n; i++) {
if(sal_sk(a[i]==true))
rez = lkd(rez, a[i]);
delete [] array;
}
So i have this code and I cant see the problem why it doesnt work, can someone help me? The functions should work so it should be their fault, i think i dont understand the arrays so good so I think there is the problem. The comments will help you understand the code thanks!
I didn't even need to read all the way down to the array part to see that this program would never work.
I'll give you a clue: sal_sk will ALWAYS return true. Also, true and false are not int.
As far as the rest of the program is concerned, it's pretty much unsalvageable. You have an open do statement that leads nowhere, main is incomplete, the ok and sal variables are unused (???). You're trying to cin data into an uninitialized pointer. That new statement uses the wrong variable, and besides it's not where it's supposed to be. The for loop starts indexing from 1 which is wrong, should be 0, and the if has the parentheses in the wrong place. The body of the loop itself destroys the array.
I suggest you delete the main function completely and start from scratch. Apart from reading a C++ book, the best suggestiong I can give you is to read your code line by line and explain to yourself what it does. If you can't, go back to the book.
A couple of hints: you don't need any do...while statement, you wanna initialize the array before you ask for the input, and you wanna ask for the input n times.

Error in program for modified bubble sort

Codeforces problem 339A-http://codeforces.com/problemset/problem/339/A
I have tried to sort the values stored at even places of the array(starting from 0).I get an error while running the program or program returns a junk value.What is wrong with my solution?
My solution:
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char s[101],temp;
int i,j;
cin>>s;
for(i=0;i<strlen(s);i+=2) //Bubble sorting values at even values of i.'+' is stored at odd values of i.
{
for(j=0;j<(strlen(s)-i-2);j+=2)
{
if(s[j]>s[j+2])
{
temp=s[j];
s[j]=s[j+2];
s[j+2]=temp;
}
}
}
cout<<s;
}
Your compiler should have warned you about the problem (you did switch on all warnings, yes? always do that!): Once i==strlen(s)-1, the loop for j is essentially unbounded, by the magic of arithmetic rules for signed/unsigned values.
for(unsigned j=0; j+2+i < strlen(s); j+=2)
does not have this problem. (i should be unsigned as well.)
Or stop the loop for i earlier. The problem in your code is still there then, but you won’t run into it. But I believe that is the worse route to take – fix the bug, and then optimize by observing i doesn’t need to go as far up, because the last character already forms a sorted sequence.
For odd lengths len of s, the outer loop runs until i==len-1. The inner loop then terminates at len - len - 1 - 2. Since strlen returns an unsigned type, this evaluates to a very large unsigned number, causing the inner loop to read way beyond the end of s. Eventually you'll reach memory you don't have access to read or write, causing the crash.
You can fix this by ending the outer loop sooner
int len = strlen(s);
for(i=0;i<len-2;i+=2) {
for(j=0;j<(len-i-2);j+=2)
Change this:
for(i=0;i<strlen(s);i+=2)
Into this:
for(i=0;i<strlen(s) - 2;i+=2)
Otherwise the s value be handled beyond its end-point
here is my code
void bubble(int a[], int n){
for(int i=0; i<n; i++){
int swaps=0;
for(int j=0; j<n-i-1; j++){
if(a[j]>a[j+1]){
int t=a[j];
a[j]=a[j+1];
a[j+1]=t;
swaps++;
}
}
if(swaps==0)
break;
}
}