string length (I'm in a hurry)

so I wrote a code and I want to get a number from user that says how many characters they're going to enter and then I want them to enter a string. the string has to calculate a few things which there is no problem with that part. my problem is that no matter where I put the cin for string size the program will ignore that line. can you help me please?
I really tried everything I knew. the moment I hit enter no matter how many cin's I put it will just show a result.
I want "k" to be the length user enters

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
  #include <iostream>
using namespace std;

int main()
{int k;
   char line[k];
    int U,D,L,R,X,Y,Z,i;
    U =  L = R = D = 0;

     cin.getline(line, k);
    for( i = 0; line[i]!='\0'; ++i)
    {
    	 if(line[i]=='U' )
        {
            ++U;
        }
        else if(line[i]=='D' )
        {
            ++D;
        }
       else if(line[i]=='L' )
        {
            ++L;
        }
        else if(line[i]=='R' )
        {
            ++R;
        }
    }
       
        Y=L-R;
        X=U-D;
        if(Y<0){
        	Y=0-Y;
        }
        if(X<0){
        	X=0-X;
        }
        Z=k-X-Y;
        cout<<Z;

   
    return 0;
}
Last edited on
you cannot do this legally; arrays are fixed size known at compile time.
so you need to either use a pointer, or use a string.

std::string has a built in length.
c-strings use strlen.

a pointer looks like
char * line;
line = new char[k];

remember c-strings need an extra location for end of string marker. I highly recommend k+1.
Last edited on
can't I at least some how put a useless cin before the string somehow?
if yes how?
sure.
int dummy;
cin >> dummy;

I tried it but the second I put in the first number and go for the second one the program stops running ant it says it needs debugging
it either does that or doesn't give an answer at all
Last edited on
What exactly is the value of K here? This is your problem.
oh I got it now thanks a lot
Topic archived. No new replies allowed.