C ++将字符串数组的元素存储到变量中 [英] C++ storing an element of a string array into a variable

查看:197
本文介绍了C ++将字符串数组的元素存储到变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在用C ++编写代码,并且对它还很陌生。我遇到了将字符串数组的元素转换为变量的问题。 cout语句dcity [selection-1]按预期工作。但是,我无法将dcity [selection-1]存储到名为离开位置的变量中。 Visual Studios给我一个错误,即从字符串到char没有合适的转换函数。有没有人建议如何正确存储此文件?谢谢!

I am currently coding in C++ and am fairly new to it. I am running into issues with converting an element of an array of strings into a variable. The cout statement dcity[selection-1] works as intended. However, I am unable to store dcity[selection-1] into a variable named departureLocation. Visual Studios gives me the error that there is no suitable conversion function from a string to a char. Does anyone have advice on how to properly store this? Thanks!

int main()
{

int selection = 0;
char departureLocation;


std::string dcity[] = { "Seattle Detroit Seattle Chicago Houston Seattle" };
std::cout << "Please choose a number from the list";
std::cin >> selection;
std::cout << dcity[selection-1];


departureLocation=dcity[selection-1]

};


推荐答案

由于C ++是一种强类型语言,因此它不会不喜欢类型不匹配。
您已通过以下方式声明了变量:

Since C++ is a strongly-typed language, it doesn't like type mismatches. You've declare your variable in the following way:

字符离开位置;

这意味着离开位置是char类型的变量或单个字符。因此'C'可以进入离开位置,但是 Chicago不能进入,因为它不仅仅是一个字符。

This means departureLocation is a variable of type char, or a single character. So 'C' can go into departureLocation but "Chicago" cannot, as it is more that one character.

您还这样声明了数组:

std :: string dcity [] =

此处,您已将数组的类型定义为std :: string。因此,数组的元素是字符串,而不是字符。

Here, you have defined the type of the array as std::string. So elements of the array are strings, not chars.

简短的回答是,在声明它时,需要将离开位置的类型更改为字符串,而不是字符像这样的东西:

The short answer is that you need to change the type of departureLocation to a string when you declare it, instead of a char. Something like:

std :: string别离Location;

在上面的代码中,我也没有看到任何包含语句。为了使C ++能够识别字符串类,您需要确保以下内容位于代码的顶部:

I also didn't see any include statements in your code above. For C++ to recognize the string class, you'll need to make sure the following is at the top of your code somewhere:

#include< ; string>

这篇关于C ++将字符串数组的元素存储到变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆