简体   繁体   English

我可以使用 printf 打印 c++ 字符串数组的元素吗

[英]can i use printf to print element of c++ array of strings

#include <iostream>
using namespace std;

int main()
{
    string s[] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
    int a, b;
    cin >> a >> b;
    for (int i = a; i <= b; i++)
        (i >= 1 && i <= 9) ? printf("%d\n", s[i - 1]) : i % 2 ? printf("odd\n") : printf("even\n");
    return 0;
}

I am using a ternary operator to print integer into word if it lies between 1 to 9 otherwise printing whether it's even or odd.如果 integer 位于 1 到 9 之间,我正在使用三元运算符将它打印成 word,否则打印它是偶数还是奇数。 I am not able to use cout in ternary operator and if I used printf then it's printing a character.我无法在三元运算符中使用 cout ,如果我使用 printf 那么它正在打印一个字符。 can anybody tell me how to do that.谁能告诉我该怎么做。 I wanted to do the entire stuff in one line, is it possible?我想在一条线上做所有的事情,这可能吗?

You can use cout .您可以使用cout Like so:像这样:

#include <iostream>


int main()
{
    std::string s[] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
    int a, b;
    std::cin >> a >> b;
    for (int i = a; i <= b; i++)
        std::cout << ((i >= 1 && i <= 9) ? s[i-1]: (i % 2) ? "odd": "even") << "\n";
    return 0;
}

%d prints decimal numers to the console. %d将十进制数字打印到控制台。 To print strings, you need the %s token and make sure that you get the const char* of it using s[i - 1].c_str() .要打印字符串,您需要%s令牌并确保使用s[i - 1].c_str()获得它的const char*

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM